A solution to async boilerplate in JavaScript ✨

Written by supermdguy | Published 2018/09/27
Tech Story Tags: javascript | vuejs | vuex | react | redux

TLDRvia the TL;DR App

Source

Have you ever written code that looks like this?

Maybe you also have error handling or a fancy delayed spinner that adds even more complexity. Writing the same code for every single async task in your project can add a lot of boilerplate, especially if you have a lot of HTTP requests in your application.

Since this is such a common problem, several solutions have already been proposed. In fact, the React team is currently working on building a solution into React itself, through React Suspense. With all these potential solutions, it might seem like isLoading boilerplate is a solved problem.

However, almost all of these solutions are tied to a framework. This isn’t necessarily a problem — frameworks can be great! However, it’d be better to have a solution that works with pure JavaScript. This would make it so you can track the state of async requests in any situation: whether it’s in your UI framework of choice, Vanilla JS, or your favorite state management solution.

For example, I do a lot of work with Vue, and I found solutions that worked well with Vuex. But, they wouldn’t work at all if I wanted to track the state of request in a component’s state instead of the global store. There’s a similar issue with most of the React solutions. A pure JavaScript solution, on the other hand, would be able to handle all the complexities of async tasks while still being flexible enough to work with almost all frontend technology stacks.

I recently released tuxi, which aims to solve the async state boilerplate problem, while still meeting the flexibility requirements I outlined. Though it has a pretty simple API, it does some really cool things:

  • Configurable delayed spinners by distinguishing between “pending” tasks and “spinning” tasks.
  • Handles scenarios where multiple instances of a request are fired quickly: only the data from the most recently fired request will be returned.
  • It can also handle multiple instances of a request where each request’s state is stored and accessed separately.
  • Supports Vue and Vuex without reactivity or strict mode errors, via a plugin.
  • Has a plugin API that will make it possible to add integration with React and Redux without too much work (open issue for a React plugin here, if you’re interested and want to give a 👍).

Examples

Pure JavaScript

Vue

Vuex

Final Notes

Tuxi is still relatively new, but it’s pretty stable. It has 100% passing unit test coverage, and I’m using it in production. Though I don’t have full documentation written yet, you can read the tests for complete usage examples. Also, feel free to create an issue if you have any questions, requests, or suggestions, and I’ll get back to you as soon as I can.

UPDATE (10/11/2018): I wrote the docs.


Published by HackerNoon on 2018/09/27