javascript / beginner
Snippet
Fetching Remote Data with Async/Await Inside React Effects
Asynchronous operations in React cannot make the useEffect callback itself an async function. Instead, declare an inner async function and invoke it immediately to await HTTP promises cleanly.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useState, useEffect } from 'react';function UserProfile() {const [user, setUser] = useState(null);useEffect(() => {async function loadUserData() {const response = await fetch('https://api.example.com/user/1');const data = await response.json();setUser(data);}loadUserData();}, []);return <div>{user ? user.name : 'Loading...'}</div>;}
react
Breakdown
1
async function loadUserData() {
Defines a nested asynchronous function capable of using the await keyword.
2
const response = await fetch('https://api.example.com/user/1');
Asynchronously requests data over HTTP and pauses execution until resolved.
3
setUser(data);
Updates the component state once asynchronous JSON parsing completes.