Compare IDs from the database

Hello everyone,

I’m seeking advice on how to optimize the code below. While it’s currently functional, I’ve been advised against querying the database within the onItemReady function. Therefore, I’m looking for a more efficient and reliable approach to achieve the same outcome.

The checkLikes() function aims to compare the IDs of two collections, namely “Music” and “Favorites”. I’m using a repeater that’s linked to the “Music” collection. My objective is to query the “Favorites” collection using the “songId” (which is a reference field from the Music collection) and compare it with the “_id” field of the Music collection. If a match is found, I want to display a liked button on the repeater items.

I’m grateful for any advice or suggestions you may have. Thank you!

export async function checkLikes() {
    $w("#repeater1").onItemReady(async ($item, itemData, index) => {
        let likesResult = await wixData.query("Favorites")
        .eq("_owner", memberId)
        .eq("songId", itemData._id)
        .find()
        console.log(likesResult);
        if (itemData._id) {
            if (likesResult.length > 0) {              
                $item('#likeBtn').hide();
                $item('#unlikeBtn').show();
            } else {             
                $item('#unlikeBtn').hide();
            }
        } else {
            if (likesResult.length > 0) {                
                $item('#likeBtn').hide();
                $item('#unlikeBtn').show();
            } else {              
                $item('#unlikeBtn').hide();
            }
        }
    });
}

The wixData query is not dependent on your repeater item being ready. So, you can perform that query then pass the resulting data to your repeater and populate your repeater items with the results of the query however you like

Thanks, I will check it!