Last active
July 13, 2023 13:39
-
-
Save SimpleCookie/c7e722fd099bd067a9c769a29ccac296 to your computer and use it in GitHub Desktop.
useFetch.sx
This file contains 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" | |
/** | |
* Example usage: | |
const App = () => { | |
const { data, error, loading } = useFetch<any>("https://jsonplaceholder.typicode.com/posts") | |
if (loading) return <div>Loading...</div> | |
if (error) return <div>Error</div> | |
if (data) <div>{JSON.stringify(data)}</div> | |
} | |
*/ | |
export function useFetch<T>(url: string) { | |
const [data, setData] = useState<T>() | |
const [loading, setLoading] = useState<boolean>(true) | |
const [error, setError] = useState<any>(null) | |
useEffect(() => { | |
const fetchData = async () => { | |
setLoading(true) | |
setData(undefined) | |
setError(undefined) | |
try { | |
const response = await fetch(url) | |
const jsonData = await response.json() | |
setData(jsonData) | |
} catch (error) { | |
setError(error) | |
} finally { | |
setLoading(false) | |
} | |
} | |
fetchData() | |
}, [url]) | |
return { loading, error, data } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment