In the following piece of code, I am taking the title & ID from the post collections and I want to update the the color of post title, likecount, and few other attributes in posts_attributes collections. This is nested in a repeater. The issue I am having is that before the update query runs fully the control jumps onto the the next item in the repeater. I tried to use the async/await to make the control wait on the current item in the repeater, but I am still not having success with that. Can anyone help?
$w.onReady(function () { $w('#postsdataset').onReady( () => { let color; let title; let postid; let count = $w("#postsdataset").getTotalCount(); $w('#repeater2').forEachItem(async($item, itemData, index) => { let likecount = itemData.likeCount; let colorcount = count-index-1; while (colorcount > 2){ colorcount = colorcount-3; } if(colorcount == 0) { $item("#titlebox").style.backgroundColor = "#DE2A6C"; colorcount++ } else if(colorcount == 1) { $item("#titlebox").style.backgroundColor = "#21C8D1"; colorcount++ } else { $item("#titlebox").style.backgroundColor = "#FFF763"; let value = $item("#titletext").text; $item("#titletext").html = "<h3 style='font-size: 13px; font-style: monsterrat; letter-spacing: 0.25; word-spacing: 0.13; color:#001D4B'>" + value + "</h3>"; colorcount = 0; } color = $item("#titlebox").style.backgroundColor; title = $item("#titletext").text; postid = itemData._id; let toInsert = { "postId": postid, "title": title // "color": color }; wixData.insert("Posts_attributes", toInsert) .then( (results) => { let item = results; //see item below } ); $item("#container2").onClick(function(){ let page = itemData.postPageUrl; console.log(page); wixLocation.to(page); }); $item('#Heart').onClick((event) => { console.log("before",likecount); likecount++; console.log("after",likecount); $item('#Heart').hide(); $item('#Heartclicked').show(); $w('#postsdataset').setFieldValue("likes",likecount); $w('#postsdataset').save(); } ); console.log (postid, title, color); await updaterecord(postid, color, likecount); }); }); });
async function updaterecord(id, color, count) { console.log (id, color, count); await wixData.query("Posts_attributes") .eq("postId", id) .find() .then( (results) => { let record = results.items[0]; record.color = color; record.likes = count; console.log(record.postId, record.title); wixData.update("Posts_attributes", record); }); return; }
It looks like the problem is with the insert into the Posts_attributes collection. You need to await the call so that the insert completes before the query and updates are called. Currently, the code isn't waiting for the insert to resolve so there isn't a record in the Post_attributes collection to find or update.
Try changing:
wixData.insert("Posts_attributes", toInsert)
.then( (results) => {
let item = results; //see item below
} );
To:
let item = await wixData.insert("Posts_attributes", toInsert);