Hi Everyone! I’m attempting to build a collection tracking website where users can log in, view all items, and add items to their collection.
I have a dynamic category repeater page setup with every item. Within the repeater is a button to add the item to your collection.
In the code attached, the first block of code is to check if the user is logged in and perform some actions, this is working correctly.
The third block of code to add the actual item to their collection is working as well. The part I’m having trouble with is the middle block.
The intent of this middle code is, when the user is logged in and the page loads, to check the collection database for the specific repeater item and logged in user. If it does not exist, show the button to add to collection. If it does exist, hide the button. I’m at a loss on where to go. It does not seem to be functioning at all.
The dataset actually attached to this repeater page is “pins”, while the collection database is named “C_pins”
Thanks in advance for any help!
import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;
//Verifies the user is logged in.
//If so, hide log in text and start collection check function.
//If not, hide the add button.
$w.onReady( function (event) {
if (wixUsers.currentUser.loggedIn) {
$w(“#pins”).onReady(() => {
$w(‘#text27’).hide();
checkcollection();
});
} else {
$w(‘#addtocpins’).hide();
}
});
//Checks the collection database (C_pins) to see if the item exists for the current user.
//If not, show the add button.
//If so, hide the add button.
function checkcollection() {
let userId = wixUsers.currentUser.id;
let product_id = $w(‘#pins’).getCurrentItem()._id;
wixData.query(‘C_pins’)
.eq(‘_id’, product_id)
.eq(‘_owner’, userId)
.find()
.then((results) => {
let count = results.totalCount;
if (count === 0) {
$w(‘#addtocpins’).label = “ADD TO COLLECT”;
} else {
$w(‘#addtocpins’).hide();
}
})
. catch ( (error) => {
let errorMsg = error.message;
let code = error.code
});
}
//Performs the action to add the item to the user’s collection when the add button is clicked.
export function addtocpins_onclick(event, $w) {
let $item = $w.at(event.context);
wixData.insert(‘c_pins’,
{c_pins_item: $w(‘#pins’).getCurrentItem()._id}),
$w(‘#addtocpins’).hide()
}