R. Anderson
R. Anderson

Reputation: 39

Set state in async function in React using two requests

I would like to fetch to APIs and store them in React hooks. The following does not work. When I do a similar pattern with just one fetch (no Promise.all) it works fine.

  const [first, setFirst] = useState(null);
  const [second, setSecond] = useState(null);
  
  useEffect(() => {
    getData();
  }, []);

  async function getData() {

    let [res1, res2] = await Promise.all([
      fetch('url1'),
      fetch('url2'),
    ]);

    const data1 = await res1.json();
    const data2 = await res2.json();

    setFirst(data1);
    setSecond(data2);

    console.log(data1); //Array as expected
    console.log(first); //null
  }

Upvotes: 0

Views: 777

Answers (1)

jsejcksn
jsejcksn

Reputation: 33931

State updates using the setState function returned by the useState hook are asynchronous (but React doesn't expose that promise to you).

If you want to react to changes in a state value from the useState hook (e.g. logging the value to the console when it changes), you can do so by including it as a dependency in the useEffect hook:

useEffect(() => {
  console.log(first);
}, [first]);

Upvotes: 1

Related Questions