B
B
baroman4ik2021-12-17 11:03:42
JavaScript
baroman4ik, 2021-12-17 11:03:42

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

1 answer(s)
A
Alexander, 2021-12-17
@baroman4ik

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 question

Ask a Question

731 491 924 answers to any question