I’m making a website where users can receive points. Based on these points, a ranking is created.
I have a data hook " afterUpdate" on a collection where the points are entered.
Once one of the records changes, a function ’ calculateScore ’ is called. This function gets the current points of the user by wixData.query() and adds the new ones to it and saves again with wixData.save().
When this function is called one by one (update the points table record by record and waiting some time between the updates) everything runs perfect.
When I update the collection with e few at the same time, the issues starting.
example:
current points: 0
- record A changes → datahook triggers and calls the updateRanking function. Inside this function, the current amount of points (0) is received via the query(), added with the amount of points (1) and saved again.
- while this is running, another record is triggered, the current amount that it received is also 0 (did the query before the first one was saved. Adds the amount of points (1) and saves.
The result is a total of 1 point where it had to be 2
import wixData from 'wix-data';
export function calculateScore(item) {
console.log(item);
return wixData.query("AnswersDailyBets")
.eq("matchid", item._id)
.eq("calculated", null)
.eq("latestBet", true)
.or(
wixData.query("AnswersDailyBets")
.eq("matchid", item._id)
.eq("calculated", false)
.eq("latestBet", true)
)
.find().then(res => {
res.items.forEach(element => {
let score = element.goalsHome
console.log(score);
return wixData.query("UserStand")
.eq("user", element.user)
.find().then(result => {
console.log(result);
let temp = result;
result.items[0].totaalAantalPunten += parseInt(score)
wixData.save("UserStand", result.items[0], { "suppressAuth": true, "suppressHooks": false })
.then((results) => {
let item = results; //see item below
console.log('after save puntenstand: ', results);
return results
})
})
})
return res
})
}
What is the correct way to solve this? How can I make sure that the second run of this function does not start before this one is done (to make sure that the save is finished)