Goal : Logged in Member is allowed to “vote” (via the ratingsinput element) on a myriad of items (contained in a dataset) but only once per item.
Problem : the member can simply refresh or return to the dynamic page and vote again.
Theory : Capture the members’ ID at each vote instance (on each item) and then query (contains) the field that it reside in to return a “you already voted” or if not found, allow to them to vote. (hide/show element)
Setup : I presently have one database containing all the information including the items details and votes. Let’s call that the “items database”. Within this database I have a field called “voterid”. I’m able to capture the logged-in members’ ID and save it to a field in the items database. (code below)
Trial & Errors : I’m able to capture the logged-in members’ ID and save it to a field however I do not know how to add to the existing data that will ultimately reside there. For example: If one member has already voted, the field would represent only their ID. I also want for the next member to vote, adding to the existing data plus a comma. (xxxx-xx-xxx, xxxx-xx-xxxx) Presently, it’ll wash out the existing value and replace it with theirs.
Help? Thanks in advance.
import wixData from 'wix-data';
import wixUsers from 'wix-users';
let user = wixUsers.currentUser;
let userId = user.id; //
let isLoggedIn = user.loggedIn; // true
user.getEmail()
.then((email) => {
let userEmail = email; //
});
// ...
$w.onReady(function () {
$w("#user1").text = user.id;
});
export function heart_change(event) {
$w("#dynamicDataset").onReady(() => {
// get the current item from the dataset
const currentItem = $w("#dynamicDataset").getCurrentItem();
// get the current average rating, number of ratings, and
//total ratings for the current dataset item
const average = currentItem.avg;
const count = currentItem.numRatings;
const total = currentItem.totalRatings;
// get the new rating from the ratings input
const newRating = $w('#heart').value;
let voterId = currentItem.user2
// calculate the new average rating based on the current
//average and count
const newAverageLong = (total + newRating) / (count + 1);
// Round the average rating to 1 decimal point
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);
// set the dataset fields to the new average, total
// ratings, and number of ratings
$w('#dynamicDataset').setFieldValues({
'avg': newAverageShort,
'totalRatings': total + newRating,
'numRatings': (count + 1),
'voterId': user.id
});
// save the dataset fields to the collection
$w('#dynamicDataset').save()
.catch((err) => {
console.log('could not save new rating');
}
);
$w("#heart").hide("fade")
});
}