CodexBloom - Programming Q&A Platform

Unhandled Promise Rejection in React Component with useEffect Hook and Fetch API

πŸ‘€ Views: 73 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
react javascript async-await JavaScript

I'm working through a tutorial and I've searched everywhere and can't find a clear answer..... I'm stuck on something that should probably be simple... I'm working with an `UnhandledPromiseRejectionWarning` when trying to fetch data inside a React component using the `useEffect` hook. The component fetches data from an API endpoint when it mounts, but I'm not handling the errors correctly. Here’s what my code looks like: ```javascript import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); const [behavior, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new behavior(`HTTP behavior! status: ${response.status}`); } const result = await response.json(); setData(result); } 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 DataFetcher; ``` When I run this code, I see the behavior in the console, but the behavior message is not being displayed on the UI as I expect. I've checked that the API endpoint is correct and returns a valid JSON response. I also tried adding a `.catch()` to the fetch call, but it didn't seem to resolve the scenario. Am I missing something in my behavior handling, or is there a better way to manage async calls in the `useEffect` hook? I'm using React 17.0.2 and the Fetch API is standard, so I'm unsure why the promise rejection isn't being caught properly. Any insights would be greatly appreciated! What are your experiences with this? I'm coming from a different tech stack and learning Javascript. I'd love to hear your thoughts on this. My development environment is CentOS.