Last active
February 19, 2026 15:49
-
-
Save Kcko/f2bf1beebd7b0e253c59d9d345eb0af4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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