BEFORE SWR: useEffect + fetch
function Profile() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch("/api/user")
.then(r => r.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error!</p>;
return <p>{data.name}</p>;
}
Problems:
- Lots of boilerplate
- Manual loading/error handling
- No caching
- No revalidation
- Mutations are painful