In a loop, how to update the state as many times as the loop? For below, the updateDataset() only update the state when the loop finishes. Is there a way to update the state along with how many times the looping occur, so that the app re-render each round of looping
const [dataset, updateDataset] = useState([]);
function bubbleSort() {
//how many rounds of comparison
var sortedArray = dataset.slice();
for (var i = sortedArray.length; i > 0; i--) {
//how many comparison pair
for (var j = 0; j < i - 1; j++) {
// console.log(arr, arr[j], arr[j + 1]);
//always compare one to the next one, that is why j+1
if (sortedArray[j] > sortedArray[j + 1]) {
//swap the value
var temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
//update state
updateDataset(sortedArray.slice())
}
}
}
}
Is there a way to update the state along with how many times the looping occur, so that the app re-render each round of looping
JS only has one event loop and blocking code (like a loop) is going to be The One Thing that JS is doing. Any state changes will be queued until the event loop is free.
What you could do is replace the loop with a recursive function which calls itself with a timer:
const example = (data, countdown) => {
const newData = doStuffWith(data);
if (countdown > 0) {
setTimeout(example, 500, newData, countdown - 1);
}
}
… but be very very careful you don’t end up with two instances of example running overlapped (from separate calls to whatever runs it for the first time).