Wait set state finishes to call another function

16 views Asked by At

I have an useEffect where i made an api request to get data and feed an array named 'opcoes' that is declarated as a React useState. So it is something like const [opcoes, setOpcoes] = useState([]). After that i get the api response it should setOpcoes with the value that i got and then call a function named 'comparaQtd()'. The problem is that this function is being called before the set state finishes and i need it to be filled to compare it with another array in the function comparaQtd(). Does anyone know how can i wait this? I have already tryed to put the set state in a promise and the otherFunction in the resolve of the promise, but it still not working...

//how it was before
setOpcoes(opcoesResponse.data); 
comparaQtd();


//how it is now with promise
const execState = () => new Promise(resolve => {
   setOpcoes(opcoesResponse.data);
   resolve();
});

execState().then(() => {
   comparaQtd();
});
0

There are 0 answers