reactjsnext.jsuse-effectuse-state

Proper use of useEffect with useState called within async function


Salutations!

I am trying (and succeeding) in copulating an array inside an async function. I am using this array to set the state of an array declared on the top level of a React Component like so:

  const [retrievedData, setRetrievedData] = useState([]);

  useEffect(() => {
    setRetrievedData;
  }, [retrievedData]);

  async function fetchInfo() {
    const promiseData = await Promise.all(<My fetch links array>)
    );

    const dataInJson = await promiseData.map((resp) => resp.json());

    let actualData = [];

    for (let i = 0; i < dataInJson.length; i++) {
      const foo = await Promise.resolve(dataInJson[i]);
      actualData.push(foo);
    }

    setRetrievedData(actualData);
  }

  fetchInfo();

The problem with this code is that it creates an infinite loop of setStates, even when I set the useEffect second parameter to an empty array. I also tried using async/await when calling the fetchInfo function but that just returns another Promise of course. While working on this, I also noticed that the Promise.all call runs twice.

I appreciate the time in reading this question.


Solution

  • This is a common pattern in react

    const Component = () => {
      const [data, setData] = useState();
    
      useEffect(() => {
        const fetchData = async () => {
          const data = await fetch();
          setData(data);
        };
    
        fetchData();
      }, []);
    
      return <div>{JSON.stringify(data)}</div>;
    };