CodexBloom - Programming Q&A Platform

Unhandled Promise Rejection with axios in React Component When Fetching Data

👀 Views: 88 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-15
react axios async-await JavaScript

I just started working with I'm not sure how to approach I'm relatively new to this, so bear with me..... I'm working with an scenario in my React application where I'm using axios to fetch data from an API. The data fetching is implemented inside a useEffect hook, but I'm experiencing an 'Unhandled Promise Rejection' when the API call fails due to network issues. I've set up my useEffect like this: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios'; const MyComponent = () => { const [data, setData] = useState(null); const [behavior, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('https://api.example.com/data'); setData(response.data); } catch (err) { setError(err); console.behavior('Fetch behavior:', err); } }; fetchData(); }, []); if (behavior) return <div>behavior: {behavior.message}</div>; if (!data) return <div>Loading...</div>; return <div>Data: {JSON.stringify(data)}</div>; }; export default MyComponent; ``` However, when the API doesn't respond, I see the behavior in the console: `UnhandledPromiseRejectionWarning: behavior: Network behavior`. I've made sure to handle the behavior in the catch block, but it still triggers the unhandled rejection. I've also checked the version of axios I'm using, which is 0.21.1. I've tried adding a global behavior handler for unhandled rejections as a quick fix, but that doesn't seem to solve the question at its root. Is there a better way to manage this in the context of React and axios? Any insights would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Thanks in advance! Is there a better approach?