DEV Community

Homebrew React Hooks: useAsyncEffect Or How to Handle Async Operations with useEffect

Laurin Quast on July 05, 2019

TLDR Async functions lack cancelability. We can use generator functions for mimicking cancelable async functions. I created a library fo...
Collapse
 
pablomayobre profile image
Pablo Ariel Mayobre

This is really cool! Is this published anywhere as a package?

Also you seem to have an error in your last example, you are doing await fetch instead of yield fetch

Thanks for this piece of code, really helpful!

Collapse
 
n1ru4l profile image
Laurin Quast

Thanks 🙏 I fixed it!

I have no package published, currently I am just copy pasting it into my projects.

Collapse
 
ancientswordrage profile image
AncientSwordRage

Please do publish it

Thread Thread
 
n1ru4l profile image
Laurin Quast

Finally got around building the package with tests: github.com/n1ru4l/use-async-effect

Thread Thread
 
ancientswordrage profile image
AncientSwordRage

Thank you

Collapse
 
frfancha profile image
Fred • Edited

Very useful! Busy to transfer a huge app from angularjs to react and I have implemented your strategy in our fetch calls. Thanks for sharing practical info!
I have also added "sleep" in the API of the server sering data to the app (c# web.api) to test all kind of scenarios and everything was working exactly as expected ;-)

Collapse
 
harjis profile image
Joonas Harjukallio

Looks really nice!

Do you know if there is a way to extend this so that it could be executed on demand? What I'm after is a basic save functionality.

What I have been doing so far is just having a callback which calls an async function. The callback is then called from the save buttons onClick handler. This of course doesn't support cleaning up so if the component gets unmounted before saving request has finished it might call setState on an unmounted component

Collapse
 
n1ru4l profile image
Laurin Quast

I thought about creating useAsyncCallback. Shouldn‘t be to hard to implement!

Collapse
 
Collapse
 
n1ru4l profile image
Laurin Quast

completely different solutions and none of them show case aborting effects upon component unmount as well as handling effect re-runs with potential race conditions :)

Collapse
 
fsjsd profile image
Chris Webb

Superb dissection of this issue and work!

Collapse
 
benstov profile image
benstov • Edited

Really nice of you to share this! I will definitely use it in dashboard I'm working on :)
Thank you