Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of useEffect with useState called within async function [duplicate]

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.

like image 880
Thanos Dodd Avatar asked Dec 09 '25 18:12

Thanos Dodd


1 Answers

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>;
};
like image 150
jkaczmarkiewicz Avatar answered Dec 11 '25 11:12

jkaczmarkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!