Last active
June 22, 2023 20:40
-
-
Save SimpleCookie/830aea97fa40eb41c02daadf498193e2 to your computer and use it in GitHub Desktop.
Fetch in react
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
export const useFetch = (url) => { | |
const [data, setData] = useState(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
const fetchData = async () => { | |
setLoading(true); | |
setError(null); | |
try { | |
const response = await fetch(url); | |
const data = await response.json(); | |
setData(data); | |
} catch (error) { | |
setError(error); | |
} finally { | |
setLoading(false); | |
} | |
} | |
fetchData() | |
}, []) | |
return { data, loading, error } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment