javascript / beginner
Snippet
Capturing and Displaying Async Fetch Errors in Component State
Asynchronous network calls can fail due to connectivity errors or server status codes. Wrapping fetch inside a standard try...catch block allows you to intercept the thrown Error object and store the error message in local state to render user-friendly feedback.
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
24
25
import { useState, useEffect } from 'react';export function SafeDataLoader() {const [errorMessage, setErrorMessage] = useState(null);useEffect(() => {async function fetchData() {try {const response = await fetch('https://api.example.com/data');if (!response.ok) {throw new Error('Network response was not ok');}} catch (err) {setErrorMessage(err.message);}}fetchData();}, []);if (errorMessage) {return <p role="alert">Error: {errorMessage}</p>;}return <p>Data loaded successfully.</p>;}
react
Breakdown
1
const [errorMessage, setErrorMessage] = useState(null);
Initializes an error state tracking variable set to null when no failure has occurred.
2
if (!response.ok) {
Checks if the HTTP response status is outside the successful 200-299 range.
3
throw new Error('Network response was not ok');
Explicitly raises an Error instance to jump into the catch block for non-2xx responses.
4
} catch (err) {
Intercepts rejected promises or thrown exceptions and updates the error state.