Answer the question
In order to leave comments, you need to log in
How to sequentially execute setState requests after the previous one in React?
There is a fetch containing 4 setState functions, and since they are asynchronous, without waiting for execution, it starts to execute the making setstate, the work of which is tied to the previous one. Please tell me how best to wait for the execution of the previous setState before the work of the new one. Here is the code:
React.useEffect(() => {
(async () => {
let data = await fetch("/arr").then((data) => {
setThemes(data.json());
setActiveTheme(() => Math.floor(themes.length / 2));
setActivePlace(() => Math.floor(themes[activeTheme].subtopics.length/2))
setIsLoad(() => false);
});
})();
}, []);
Answer the question
In order to leave comments, you need to log in
React.useEffect(() => {
(async () => {
try {
const themes = await fetch("/arr").then((data) => data.json());
const activeTheme = Math.floor(themes.length / 2);
const activePlace = Math.floor(themes[activeTheme].subtopics.length / 2);
setThemes(themes);
setActiveTheme(activeTheme);
setActivePlace(activePlace);
} finally {
setIsLoad(false);
}
})();
}, []);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question