I have a YouTube video if you'd rather watch ππΏ.
Why useFetch?
It's very common to fetch data when the user goes to a certain page....
For further actions, you may consider blocking this person and/or reporting abuse
Hello, I've created a typescript version of this with the ability to make different type of requests and destroying old requests. Use useFetch for fetching on mount and useMyFetch for triggering requests. Never write another fetch request again :).
PS: dev.to Devs, add an overflow for long code blocks.
Very good article, it's good not to repeat and also isolate the logic of the component.
One tip, for me mixing the load state between a string and a boolean is a bit confusing, I know JS allows you to do this and a non-empty string is truthy but personally I think it's better to keep the same data type throughout the application, especially when you are using it only as a flag not to display content.
The different states you have there are closely related so it might be a good idea to use a useReducer, check this article by Kent C. Dodds I bet it will be useful to improve the hook.
Agreed. I used useReducer on my previous article (dev.to/techcheck/react-hooks-usere...). Good call on Kent's article π.
Awesome this article very clear thank you so much ! i like that
How can we call the custom hook on button click event?
You would need a new hook in that case, one that returns the actual function instead of calling it inside
useEffect
, something like:You could also add a parameter to disable the fetch on mount instead of creating a whole new hook.
Great article and very clear. Thanks! I've extended the logic a bit to work with TypeScript and data besides a URL in case anyone else has a use case where a user action triggers a need to re-fetch data.
this is great thank you!
Thanks!
Good write up on the hook. I was looking to create a useFetch hook and came to this, though my intention was completely different.
I was looking to create an useFetch hook that returns a fetch function that handles all the error (displaying them in snackbar), so you will end up handling all the error in one place.
For the same functionality in your write up, with additional feature to memorize and caching the results, may I also recommend useSWR. It's created by the same people behind NextJS and vercel and it's really good.
Wow, great! Good call thank you
Ah, this is exactly what I've been looking for - I'd love to extend it with configurable options like get vs post, and other things like headers for auth for example. Great!
For sure! And thanks! π
Please fix code issue, close useFetch function correctly, add "}" this character to end of line