javascript / beginner
Snippet
Fetching Remote Data Asynchronously Inside useEffect
Asynchronous operations such as HTTP requests use async/await alongside try...catch blocks. Handling network failures gracefully prevents uncaught promise rejections and allows rendering friendly fallback UI.
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
import React, { useState, useEffect } from 'react';function UserProfile({ userId }) {const [user, setUser] = useState(null);const [errorMessage, setErrorMessage] = useState('');useEffect(() => {async function loadData() {try {const res = await fetch(`https://api.example.com/users/${userId}`);if (!res.ok) throw new Error('User not found');const data = await res.json();setUser(data);} catch (err) {setErrorMessage(err.message);}}loadData();}, [userId]);if (errorMessage) return <p>Error: {errorMessage}</p>;if (!user) return <p>Loading...</p>;return <h2>{user.name}</h2>;}
react
Breakdown
1
async function loadData() {
Declares an asynchronous inner function to await network calls within the effect hook.
2
try { ... } catch (err) {
Catches potential runtime network or parsing errors to store the message in state.