Yet another pattern for API calls using vuejs/vuex

larbi jirari
Vue.js Developers
Published in
2 min readAug 26, 2019

--

Do you manage API calls in a Vuex store ? this article is for you, by the end of this article a codesandbox example is provided.

API calls have three main status: Pending, Success, Fail

To manage these three status in most case I've seen developers creating action(s),mutation(s),getter(s) per state.

In the previous example we had to write all that code to handle one ajax call, imagine having multiple ajax calls thus you’ll have to write the same thing over and over.

adding another ajax call:

as you see it becomes quite tedious to manage.

with that being said, i decided to produce a util class to manager states in a smarter way.

Let’s have a look on our store after a Refactoring using the util class,

let’s have a look on the util class:

there is two functions that are essentials in this class

state(…) => Inits the state by creating an object and returning it.

updateState(…) =>updates the state with the given data it could be data or an Error in the case of Fail.

to wrap it up here’s a codesandebox example to a demonstrate all of the above.

Disclaimer: for a demo purpose, i wrote a fake axios to avoid having CORS problems.

--

--