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 = “
” + value + “
” ;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 ;
}