Created
January 5, 2024 18:12
-
-
Save trevsm/31f5fac826211626ae0683802c96a0c0 to your computer and use it in GitHub Desktop.
A generic react fetch hook
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 { useState } from 'react'; | |
function useFetch({ onSuccess, onError }) { | |
const [data, setData] = useState(null); | |
const [loading, setLoading] = useState(false); | |
const [error, setError] = useState(null); | |
const handleFetch = async (url, options = {}) => { | |
setLoading(true); | |
setError(null); | |
try { | |
const response = await fetch(url, options); | |
if (!response.ok) { | |
throw new Error('Network response was not ok'); | |
} | |
const jsonData = await response.json(); | |
setData(jsonData); | |
if (onSuccess) { | |
onSuccess(jsonData); | |
} | |
} catch (err) { | |
setError(err); | |
if (onError) { | |
onError(err); | |
} | |
} finally { | |
setLoading(false); | |
} | |
}; | |
return { data, loading, error, handleFetch }; | |
} | |
export default useFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment