Created
March 8, 2024 23:56
-
-
Save cheskoxd/127c2d29754e457d68f3567afa8f301b 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"; | |
export const useFetch = <T>(url: string) => { | |
const [data, setData] = useState<T | any>(); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState<Error | null>(null); | |
useEffect(() => { | |
const fetchData = async () => { | |
try { | |
const response = await fetch(url); | |
const jsonData = await response.json(); | |
setData(jsonData); | |
} catch (err:any) { | |
setError(err); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
fetchData(); | |
}, [url]); | |
return { data, loading, error }; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment