DEV Community

Cover image for Custom React useFetch() hook for data fetching with revalidation

Custom React useFetch() hook for data fetching with revalidation

damilola jerugba on December 27, 2021

This guide is to show you how to create a simple react hook for data fetching (with revalidation). 🤨 Why this hook? When fetching data ...
Collapse
 
zaheeralii profile image
ZaheerAlii

Cool Work, But I'm agree with one of the user that could you add some cancel request.

Collapse
 
chema profile image
José María CL

Nice! Working with graphql I saw a hook called useQuery which returns loading, data, error and refetch.

So, after some attempts to decouple the gql or rest implementation we've created a hook very similar to your useFetch which returns the four variables like the useQuery.

I think that the loading flag could be useful for this hook too. You know, we can infer it if the data has a value but the loading will help you to know if there is a "fetching" task in progress

Collapse
 
damiisdandy profile image
damilola jerugba

Yeah, I kept thinking whether I should add a loading value or not, I initially did but I removed it, You can contribute to the repo.

Collapse
 
activenode profile image
David Lorenz

Isn' that what SWR does? Why not go with Standards?

Collapse
 
damiisdandy profile image
damilola jerugba

It’s always fun to build and know how things work

Collapse
 
activenode profile image
David Lorenz

I agree. But for production it's mostly better to go with the standards 🤗

Collapse
 
pcelac profile image
Aleks

From quick look of example code, it will show loading state for infinite time, if your api call fails.

Collapse
 
damiisdandy profile image
damilola jerugba • Edited

It sets error to true, which displays

if (error) {
    return <h2>Error fetching users</h2>;
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kylesureline profile image
Kyle Scheuerlein

Are you sure? It looks like data would be falsy (if the fetch errors out!) and so your second if block can never run.

Thread Thread
 
damiisdandy profile image
damilola jerugba • Edited

git clone the repo and look for yourself, if this is really an issue please add an issue to the repo or try to contribute to it 💜

Collapse
 
damiisdandy profile image
damilola jerugba

Thank you

Collapse
 
minnyww profile image
apisit Amunayworrabut

Can u add cancel request when components is unmount

Collapse
 
damiisdandy profile image
damilola jerugba

Hmmm, Could you add it as a GitHub issue