- Forums
- react
- React Run Code After Usestate Has Been Updated Or Completed
this shows you a snippet of javascript code when you need to run a console after useState has been completed [5191], Last Updated: Mon Jun 24, 2024
cathy
Sun Aug 27, 2023
0 Comments
308 Visits
Example:
setCurrentQuestionIndex((currentQuestionIndex) => {
// increment the curren array index
let QuestionIndex = currentQuestionIndex + 1;
// run the Function or code with the new index
startCanvas(
pageWidth,
questions[QuestionIndex].activeBondField,
linePairs,
QuestionIndex
);
// return the index value to be used by setCurrentQuestionIndex() useState
return QuestionIndex;
});
To update the useState after it has completed, you can use this function example:
This worked for me on 9/27/2023 at /f/apachefriends/xampp/htdocs/websor/pre-school/math/NumberBods/APP/number-bonds
setCurrentQuestionIndex( (currentQuestionIndex) => {
let QuestionIndex = currentQuestionIndex+1;
startCanvas(pageWidth,questions[QuestionIndex].activeBondField,linePairs,QuestionIndex);
return QuestionIndex;
});
It did tno work for me but you can try ig. Resource: https://stackoverflow.com/a/75219742
//setTasks(new_tasks); // return a new data object
setTasks((new_tasks) =>{
console.log(`LINE 99q =Tasks`, Tasks);
return Tasks;
}); // return a new data object