Hi, I’m having a problem I can’t quite understand, I’m using the data API get() function to return an item in my data collection. I want to find field values for the item and then update them. However my variables which I give values to in the get() function end up undefined again. My code looks like this:
var cPoints; var sectionName;
wixData.get(“Score”, mcq.section)
.then((results) => { let score = results;
cPoints = score.points;
sectionName = score.title;
console.log(“score before:”, cPoints, " title before:“, sectionName);
})
. catch ((err) => { let errorMsg = err;
});
console.log(“score after:”, cPoints, " title after:”, sectionName);
The first console log returns the correct values from the data collection but the second console log reveals that these variables become undefined after the get() function. How can I fix this so the variable values persist and I can use them in other places in my code.
The reason you got at the second console undefined variables is because, get() is a async function that return a promise. As a result, the program continue to run to the second console before the promise’s resolve has returned.
You can add async and await to your code in order to pause the async function and wait for the promise to resolve prior to moving on.
async function getItem(){
var cPoints;
var sectionName;
await wixData.get("Score", mcq.section)
.then((results) => {
let score = results;
cPoints = score.points;
sectionName = score.title;
console.log("score before:", cPoints, " title before:", sectionName);
})
.catch((err) => {
let errorMsg = err;
});
console.log("score after:", cPoints, " title after:", sectionName);
}
Hey Sapir,
This is late but thank you so much, I would never has figured out the promises issue, even though it seems obvious in hindsight.
Since the code I had was inside an onclick event I finally got it to work by replacing