Saturday, February 12, 2022

Cancellable Promises

 Have you ever been in a situation where React tried to update a component that has been already unmounted?

This can be easily witnessed when your business logic is relying on some asynchronous code that would update the state once a promise resolved.

How can we prevent that from happening?

Meet cancellable.


So why is this so cool? And how can I use this?

Do you remember that useEffect has a cleanup method? That's the function that's returned inside the useEffect's callback method. You can take care of situations when components are unmounted e.g.

Sounds familiar? That's the problem we started with!

So basically, if you return a cancellable inside a useEffect, it takes care automatically of the cleanup as it's gonna set the cancelled variable, and later when trying to do some state updates, our logic will prevent that because of this peace of code: .then((v) => cancelled || ok(v)). cancelled will prevent from calling the ok method (in our case it could be a setState).

And that's it! Now you have a neat little function that is taking care of Promises that are still unfinished by the time the component has already been unmounted!