javascript / beginner
Snippet
Async Data Fetching with Error Handling in useEffect
When fetching data in React, use an inner async function inside useEffect wrapped in a try/catch block. This allows you to handle network failures or HTTP errors gracefully by updating dedicated error state instead of leaving the application in an unhandled failure state.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useState, useEffect } from 'react';function UserProfile({ userId }) {const [data, setData] = useState(null);const [error, setError] = useState(null);useEffect(() => {async function loadUser() {try {const res = await fetch(`/api/users/${userId}`);if (!res.ok) throw new Error('Failed to load');const json = await res.json();setData(json);} catch (err) {setError(err.message);}}loadUser();}, [userId]);if (error) return <p>Error: {error}</p>;return <div>{data ? data.name : 'Loading...'}</div>;}
react
Breakdown
1
async function loadUser() {
Declares an asynchronous helper function inside the effect callback.
2
if (!res.ok) throw new Error('Failed to load');
Checks the HTTP response status and throws an error for failed responses like 404 or 500.
3
} catch (err) {
Catches any network or parsing exceptions and routes them to local state.
4
if (error) return <p>Error: {error}</p>;
Renders an informative error message to the user if data loading failed.