CodexBloom - Programming Q&A Platform

Unhandled Promise Rejection when Fetching Data in React with Axios on Component Mount

👀 Views: 926 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
react axios javascript async-await JavaScript

I've been working on this all day and I'm experiencing an `Unhandled Promise Rejection` behavior when trying to fetch data using Axios in a React functional component. I'm using React version 18 and Axios version 0.21.1. The fetching is done inside a `useEffect` hook, and I'm trying to set the response data to a state variable. Here's the relevant code snippet: ```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('behavior fetching data:', 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; ``` The behavior occurs as soon as the component mounts, and the console shows `Uncaught (in promise) behavior: Network behavior`. I've checked the API endpoint and it works in Postman. I've also tried adding a catch block, but it seems like the behavior handling isn't catching the rejection correctly. I've also verified CORS settings on the server and ensured that the request URL is correct. Can anyone guide to debug this scenario or suggest best practices for handling such cases in React with async/await? I'm developing on Linux with Javascript. Any ideas what could be causing this?