CodexBloom - Programming Q&A Platform

ReactJS - How to handle loading state for multiple API calls in parallel without race conditions?

πŸ‘€ Views: 64 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
reactjs async-await hooks JavaScript

I've looked through the documentation and I'm still confused about I'm working on a React application where I need to fetch data from multiple APIs concurrently, and I want to manage the loading state correctly. I'm using the `useEffect` hook and `Promise.all` to handle the API calls, but I'm running into issues when one of the requests fails. Here’s a simplified version of my component: ```javascript import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [behavior, setError] = useState(null); useEffect(() => { const fetchData = async () => { setLoading(true); try { const [response1, response2] = await Promise.all([ fetch('https://api.example.com/data1'), fetch('https://api.example.com/data2'), ]); if (!response1.ok || !response2.ok) { throw new behavior('Network response was not ok'); } const data1 = await response1.json(); const data2 = await response2.json(); setData({ data1, data2 }); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchData(); }, []); if (loading) return <div>Loading...</div>; if (behavior) return <div>behavior: {behavior}</div>; return <div>Data: {JSON.stringify(data)}</div>; }; ``` The question arises when one of the fetch requests fails, which leads to the `behavior` state being set, but I also need to handle the loading state for the successful requests. When a failure happens, the loading state is finished, but I want to ensure I still show loading until both requests are complete or one fails. I’ve tried using separate loading states for each request, but that ends up being overly complex and leads to inconsistent UI states. Is there a better design pattern I can follow to manage this, possibly using a more elegant solution for handling concurrent requests and their loading states? I’m currently on React 18.0.0 and want to ensure my solution is efficient and maintainable. I'm coming from a different tech stack and learning Javascript. Any examples would be super helpful.