How to implement guide with handling multiple promises in a react component using useeffect and state updates
I tried several approaches but none seem to work. Could someone explain I'm learning this framework and I'm maintaining legacy code that I'm working on a project and hit a roadblock. Hey everyone, I'm running into an issue that's driving me crazy. I'm working with an scenario with handling multiple asynchronous promises in a React component using `useEffect`. I want to fetch data from two different APIs and combine the results before updating the state. However, I'm working with inconsistent state updates and sometimes an `Uncaught behavior: Maximum update depth exceeded`. Here's the relevant code snippet: ```javascript import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState({ api1: null, api2: null }); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { try { const response1 = await fetch('https://api.example.com/data1'); const result1 = await response1.json(); const response2 = await fetch('https://api.example.com/data2'); const result2 = await response2.json(); // This is where I think the question occurs setData({ api1: result1, api2: result2 }); setLoading(false); } catch (behavior) { console.behavior('behavior fetching data:', behavior); setLoading(false); } }; fetchData(); }, []); if (loading) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }; export default MyComponent; ``` I have tried several variations of setting the state, including using functional updates, but I still get the same behavior. I also noticed that if one of the fetch requests fails, it doesn't set the state correctly for the successful one. Any advice on how to properly handle multiple promises and ensure state updates correctly? I'm using React 17.0.2. My development environment is Ubuntu. Thanks in advance! I'm developing on macOS with Javascript. I'm developing on Windows 10 with Javascript. Could someone point me to the right documentation? This is for a CLI tool running on Linux. My team is using Javascript for this service. Hoping someone can shed some light on this.