Handling Fetch Errors
Learn how to handle errors when fetching data and display error messages.
Always handle network errors gracefully.
Error Handling
const [error, setError] = useState(null);
useEffect(() => {
fetch("http://localhost:8000/blogs")
.then(res => {
if (!res.ok) throw Error("Could not fetch data");
return res.json();
})
.then(data => {
setBlogs(data);
setIsPending(false);
setError(null);
})
.catch(err => {
setIsPending(false);
setError(err.message);
});
}, []);Displaying Errors
{error && <div className="error">{error}</div>}