Handling Multiple Promises in React with useEffect Causing State Stale Closure Issues
I'm reviewing some code and I'm dealing with I'm facing an issue where I am trying to fetch data from multiple APIs inside a `useEffect` hook in my React application. The problem arises because I'm using state variables to store the fetched results, and I suspect I might be running into stale closures, resulting in state not updating as expected. Hereβs a simplified version of what my code looks like: ```javascript import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data1, setData1] = useState(null); const [data2, setData2] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData1 = async () => { const response = await fetch('https://api.example.com/data1'); const result = await response.json(); setData1(result); }; const fetchData2 = async () => { const response = await fetch('https://api.example.com/data2'); const result = await response.json(); setData2(result); }; const fetchData = async () => { await Promise.all([fetchData1(), fetchData2()]); setLoading(false); }; fetchData(); }, []); if (loading) return <div>Loading...</div>; return <div>Data1: {JSON.stringify(data1)}, Data2: {JSON.stringify(data2)}</div>; }; export default MyComponent; ``` In this setup, the `loading` state is initially `true`, but I'm noticing that even after the data is fetched, it sometimes doesn't update correctly, or it seems to reflect previous states instead of the latest ones. I've also tried adding `data1` and `data2` to the dependency array of `useEffect`, thinking this might help ensure the latest values are used, but it led to an infinite loop of fetching because those states were being updated within `useEffect`. What can I do to manage these asynchronous calls properly without running into stale closure issues? Is it better to use a single state to manage both fetch results or is there a different pattern I should adopt? Any advice or best practices would be greatly appreciated! This is for a REST API running on Windows 11. How would you solve this? I'm coming from a different tech stack and learning Javascript. Any suggestions would be helpful.