React
Beginner
1 min read
Data Fetching with useEffect and fetch
Example
import { useState, useEffect } from 'react';
function usePosts() {
const [posts, setPosts ] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError ] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
signal: controller.signal,
});
if (!res.ok) throw new Error(`HTTP error ${res.status}`);
const data = await res.json();
setPosts(data.slice(0, 10));
} catch (err) {
if (err.name !== 'AbortError') setError(err.message);
} finally {
setLoading(false);
}
}
load();
return () => controller.abort();
}, []);
return { posts, loading, error };
}
function PostList() {
const { posts, loading, error } = usePosts();
if (loading) return <p>Loading posts…</p>;
if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;
return (
<ul>
{posts.map(post => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
);
}