DEV Community


Managed async actions in Mobx-State-Tree

jetako profile image Jesse Cooper ・2 min read

In every frontend project I've worked on, dealing with the boilerplate around asynchronous actions was a major pain point. Setting status flags and wrapping api requests in try/catch blocks gets old fast, and doing it in an ad-hoc fashion is messy and error-prone.

Mobx-State-Tree's flow provides a solid foundation for dealing with async actions, but we're still left to do all of the bookkeeping ourselves.

Let's look at an example adapted from their docs:

There's more lines of boilerplate here than for the actual important stuff. Doesn't seem too bad in isolation, but multiply it by the number of api requests in your app and it starts to build up. Also, this example doesn't really deal with the error. What if you need to present a specific error message to the user? You'd have to keep that in your state as well.

What if your action needs to be cancelable, or you have a chain of async actions, and you want the parent to report if the child failed? Surely you can do this manually, but only with a bunch of extra bookkeeping.

To solve these issues, I wrote a library that records the various states of your async actions and provides control over their lifecycles:


Let's compare with the above example:

No bookkeeping, and looks cleaner, in my opinion. The task runner records the pending/complete/failed state of the action in fetchProjectsTask, and an error if thrown. This gives you all the info you need to present the request state to the user.

For more complex use-cases, check out the README.

I hope some of you find this useful. Cheers!

Discussion (0)

Editor guide