Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import { useState, useEffect } from 'react'; function DataFetcher({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // Reset state when userId changes setLoading(true); setError(null); let cancelled = false; // cancellation flag async function fetchUser() { try { const res = await fetch(`/api/users/${userId}`); if (!res.ok) throw new Error('Failed to fetch'); const data = await res.json(); if (!cancelled) { setUser(data); setLoading(false); } } catch (err) { if (!cancelled) { setError(err.message); setLoading(false); } } } fetchUser(); // Cleanup: cancel stale request return () => { cancelled = true; }; }, [userId]); // re-run whenever userId changes if (loading) return <p>Loading…</p>; if (error) return <p>Error: {error}</p>; return <p>Hello, {user?.name}</p>; }
Result
Open