Skip to content

Instantly share code, notes, and snippets.

@SimpleCookie
Last active June 22, 2023 20:40
Show Gist options
  • Save SimpleCookie/830aea97fa40eb41c02daadf498193e2 to your computer and use it in GitHub Desktop.
Save SimpleCookie/830aea97fa40eb41c02daadf498193e2 to your computer and use it in GitHub Desktop.
Fetch in react
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