Making HTTP requests is a common task for most Single Page Applications. Due to the asynchronous nature of network requests, we need to manage the ...
For further actions, you may consider blocking this person and/or reporting abuse
Nice article but you should look into AbortController for that
subscribed
part as this would also cancel the actual request if it is ongoing:Thanks for the suggestion! This
AbortController
solution makes more explicit the cancel operation. Anyways, I don't use it very often because of the low browser support. Maybe, I should start using it shipping a polyfill for older browsers ๐ค.If you are worried about browser support, axios offers a similar API on top of XHR or go the polyfill way as you have said.
how can i use this hook for submitting a form? it gives me an error because it's calling inside the submitHandler function. Or it's better just to write an asynchronous function for this?
This hook cannot work for mutation requests, like form submissions, because it starts the fetch request as soon as the component is mounted. If you need to handle form submissions you should write a "classic" async handler.
Great tutorial!
Making
fetch
useful in more and more React scenario's will however become more complex over time. This video aboutreact-query
shows what I mean: youtube.com/watch?v=seU46c6Jz7EI'm not saying you should use
react-query
and I encourage people to write things themselves before they grab a library. But it's nice to have an option in the back of your head when you reach the point where you are saying to yourself: "ouch, this is becoming too complex".Thanks for the feedback! I know
react-query
and I agree with you that it's more suitable in complex web apps. That's what I wrote just before the "Connect" title ๐, maybe you missed it.Ahh yeah, I must have skipped over it.
Maybe I should have talked more about React Query because it is a very powerful library, as you said. Thanks to your comment, this tip has gotten the space it deserves ๐.
Great article on useFetch
Thanks for adding TS and Testing around the hook
nice article, the useFetch hook reusable.one thing to think about is you can also implement HOC say FetchHOC that renders the child component based in the state of the async action(calling API). that way your code will be even more reusable
Thanks for the suggestion! Generally speaking, I prefer the hooks approach because it's more explicit, but it's just a matter a preference. With an HOC we also need to handle props collision, if the component needs to make 2 request. Anyway, I'll try to refactor the hook in a HOC to see if it's even more practical.
this is awesome thank you!
perfect๐ , thaknks๐