Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active February 19, 2026 15:49
Show Gist options
  • Select an option

  • Save Kcko/f2bf1beebd7b0e253c59d9d345eb0af4 to your computer and use it in GitHub Desktop.

Select an option

Save Kcko/f2bf1beebd7b0e253c59d9d345eb0af4 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
import BlogList from "./BlogList";
import useFetch from "./useFetch";
const Home = () => {
const { error, isPending, data: blogs } = useFetch('http://localhost:8000/blogs')
return (
<div className="home">
{ error && <div>{ error }</div> }
{ isPending && <div>Loading...</div> }
{ blogs && <BlogList blogs={blogs} /> }
</div>
);
}
export default Home;
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setTimeout(() => {
fetch(url)
.then(res => {
if (!res.ok) { // error coming back from server
throw Error('could not fetch the data for that resource');
}
return res.json();
})
.then(data => {
setIsPending(false);
setData(data);
setError(null);
})
.catch(err => {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
})
}, 1000);
}, [url])
return { data, isPending, error };
}
export default useFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment