I'm trying to build a custom hook that will handle loading and error behavior of an async call.
I'd like to use it like so :
const { loading, error} = useFetch(fetchUser, id)
or
const {loading, error } = useFetch(updateUserName, id, name)
I have something that look like this so far :
function useFetch(fetchFn, ...params) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
fetchFn(...params)
.then(() => {
setLoading(false);
})
.catch(() => {
setError(true);
});
}, [...params, fetchFn]);
return { loading, error };
}
I'm having trouble with the useFetch(fetchFn, ...params)
since a new params
array is created on every call. So I cannot use it in the dependency array. But i can't use spread operator.
Is it possible to achieve what i'm trying to do ?
params
. ie:useFetch(fetchUser, id)
oruseFetch(updateUserName, id, name)
– BombarduseFetch
? From where those parameters come from (state, props, static). Probably the solution here is to wrapfetchFn
into anuseCallback
to ensure it's stable, and memoizeparams
. But it's hard to guess without knowing the origin ofparams
– TrenttrentouseCallback
. I definitely need to memo theparams
but it's not clear to me how to. – Bombard