Created
October 29, 2023 19:46
-
-
Save mcanv/9189757ec47b973b1b345f6ad131108e to your computer and use it in GitHub Desktop.
Fetch Component
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
| const { data, error, isLoading } = useFetch<FetchResult<object | any>>( | |
| `https://jsonplaceholder.typicode.com/todos/1` | |
| ); | |
| useEffect(() => { | |
| console.log(data, error, isLoading); | |
| }, [data, error, isLoading]); |
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"; | |
| export interface FetchResult<T> { | |
| data: T | null; | |
| error: Error | null; | |
| isLoading: boolean; | |
| } | |
| export function useFetch<T>(url: string): FetchResult<T> { | |
| const [data, setData] = useState<T | null>(null); | |
| const [error, setError] = useState<Error | null>(null); | |
| const [isLoading, setLoading] = useState(true); | |
| useEffect(() => { | |
| async function fetchData() { | |
| try { | |
| const response = await fetch(url); | |
| if (!response.ok) { | |
| throw new Error(`HTTP error! Status: ${response.status}`); | |
| } | |
| const json: T = await response.json(); | |
| setData(json); | |
| } catch (e: any) { | |
| setError(e); | |
| } finally { | |
| setLoading(false); | |
| } | |
| } | |
| fetchData(); | |
| }, [url]); | |
| return { data, error, isLoading }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment