CodexBloom - Programming Q&A Platform

How to manage multiple asynchronous API calls in React with proper error handling?

๐Ÿ‘€ Views: 237 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-06
React Axios API JavaScript

I've been struggling with this for a few days now and could really use some help... I'm converting an old project and Hey everyone, I'm running into an issue that's driving me crazy... I've been researching this but After trying multiple solutions online, I still can't figure this out. I'm working on a personal project and Currently developing a dashboard application using React and Axios. My goal is to fetch data from two different APIs concurrently and display their results. I've set up the component to call these APIs using `Promise.all`, but Iโ€™m having trouble managing errors that might come from either call. If one API fails, I want to handle that gracefully without disrupting the other API's data fetching. Hereโ€™s what I have so far: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios'; const Dashboard = () => { const [data1, setData1] = useState(null); const [data2, setData2] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const [response1, response2] = await Promise.all([ axios.get('https://api.example.com/data1'), axios.get('https://api.example.com/data2') ]); setData1(response1.data); setData2(response2.data); } catch (err) { setError('Failed to fetch data: ' + err.message); } }; fetchData(); }, []); if (error) { return <div>{error}</div>; } return ( <div> <h1>Dashboard</h1> <div>Data 1: {JSON.stringify(data1)}</div> <div>Data 2: {JSON.stringify(data2)}</div> </div> ); }; export default Dashboard; ``` In the above code, when I run this, if the first API fails, I see the error message displayed, but `data2` gets ignored completely. What Iโ€™d like to achieve is to still get the results from `data2` even if `data1` fails. Iโ€™m exploring ways to handle each API call independently, so if one fails, it doesnโ€™t affect the other. Any suggestions on how to modify this pattern to achieve that would be greatly appreciated! I'm working on a web app that needs to handle this. I'd really appreciate any guidance on this. My development environment is Ubuntu. Is there a better approach? Could someone point me to the right documentation? I'm on Ubuntu 20.04 using the latest version of Javascript. I appreciate any insights! I'm using Javascript latest in this project.