Fetching data from an external or internal API is a common use case for web applications. With react functional components, there are different hoo...
For further actions, you may consider blocking this person and/or reporting abuse
Awesome!
What about the case where you make an async request and immediately switch to another screen? React will complain that it cannot re-render an unmounted component or something like that. Is there a way to cancel the request?
I think this is a question for Thành Trang?
My sugesstion:
The hook should take a promise as param. It will more flexible than take
url
You can use fetch, axios, or any HTTP client library.
Fetch ex.:
I prefer return type same as React.useState api.
More easier for naming.
Alot of case, you will need more than 2 api calls. So you can:
Using promises improves the flexibilty of your app, in my case I'm happy to stay with the synchronous call and having a timeout barrier.
Nice read Sabastian!
I recently inherited a project that had something similar, and, it took me quite a bit of time to get familiar with the magic it had abstracted. Your's looks a lot easier to follow to say the least.
swr.now.sh is also a great alternate that takes care of some additional magic if anyone reading doesn't feel like maintaining their own fetch hook.
Hi Jamie, that's a good link you provided. Indeed there are several fetch hooks on Github and other sources. My article is primary a tutorial to get into hooks and understand them. Once familiar, more complex implementations and examples become accessible.
Shouldn't the load function be in a
useCallback
hook? When you call it from auseEffect
hook, you must add the load function into the dependency array. If you add it, that causes an infinite loop as theload
function gets recreated on every render.where is the repo?
Hi Jospeh, I don't yet publish code on Github, but you can see the final component code above.