I have a component and inside of it I am communicating with API (here I put timeout instead for simulation). I make some calls inside for loop to update arrays on current interation indexes. Finnally I want to console.log all arrays with added data. And here is the problem. Loop is going through all iterations and doesn't wait to finish asynchonous tasks so it's printing empty arrays with annotation that there are data but just came now.
I tried to add useState but I didn't solve the problem.
import React, {useEffect} from 'react';
function Ingredients() {
const heatingStepsTime = [];
const heatingStepsTimer = [];
function getTimes(i, type) {
if (type === "time") {
setTimeout(() => {
heatingStepsTime[i] = i;
}, 1000);
} else {
setTimeout(() => {
heatingStepsTimer[i] = i + 1;
}, 1000)
}
}
const getProcess = () => {
for (let i = 0; i < 3; i++) {
getTimes(i, "time");
getTimes(i, "timer");
}
};
useEffect(getProcess, []);
console.log(heatingStepsTime);
console.log(heatingStepsTimer);
return (
<div className="App">
test
</div>
);
}
export default Ingredients;
Is there a way to stop for loop iteration in React so it will continue when asychronous tasks are done?