...

/

Managing API State with Vuex

Managing API State with Vuex

Learn how to manage state and API requests via Vuex.

We'll cover the following...

Vuex

Using Vuex for managing API state is generally not recommended, because we should try to use Vuex as little as possible. Vuex is a library that’s used for global state management. Sometimes, we’re using the same state in multiple components. If the state is changed in one component, we have to update all components.

However, if we want to use it for fetching app config data for example, then the code below shows how we can go about it with Vuex.

First, here’s a dummy API function that fetches app config.

Press + to interact
// api/appConfigApi.js
export const fetchAppConfig = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({
data: {
app_name: "TheRoadToEnterprise",
version: 1,
},
});
}, 2000);
});
};

Now, let’s say we have a Vuex module called appConfig. We’ll need four files in this module:

The appConfig.js file (state). The appConfigGetters.js file (getters). The appConfigActions.js file (actions). The appConfigMutations.js file (mutations).

In the appConfig.js, we have a state for the appConfig object, API status, error, and error message.

Press + to interact
//store/modules/appConfig/appConfig.js
import getters from "./appConfigGetters";
import actions from "./appConfigActions";
import mutations from "./appConfigMutations";
import { apiStatus } from "@/api/constants/apiStatus"; const { IDLE } = apiStatus;
const state = {
appConfig: {}, fetchAppConfigStatus: IDLE, appConfigError: null, appConfigErrorMessage: "",
};
export default { state,
getters,
actions,
mutations,
};

For this ...