Being new to both Vue Webpack and Vuex after transitioning from the Ember world, I have set up my Vue Webpack app with Vuex using vue-resource in two different files:
/src/store/api.js
import Vue from 'vue';
import { store } from './store';
export default {
get(url, request) {
return Vue.http
.get(store.state.apiBaseUrl + url, request)
.then(response => Promise.resolve(response.body))
.catch(error => Promise.reject(error));
},
post(url, request) {
return Vue.http
.post(store.state.apiBaseUrl + url, request)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
// Other HTTP methods removed for simplicity
};
The above api.js file is then imported into my /src/store/store.js file as shown below:
import Vue from 'vue';
import Vuex from 'vuex';
import Api from './api';
Vue.use(Vuex);
// eslint-disable-next-line
export const store = new Vuex.Store({
state: {
apiBaseUrl: 'https://apis.myapp.com/v1',
authenticatedUser: null,
},
mutations: {
/**
* Updates a specific property in the store
* @param {object} state The store's state
* @param {object} data An object containing the property and value
*/
updateProperty: (state, data) => {
state[data.property] = data.value;
},
},
actions: {
usersCreate: (context, data) => {
Api.post('/users', data)
.then(response => context.commit('updateProperty', { property: 'authenticatedUser', value: response.body }))
// eslint-disable-next-line
.catch(error => console.error(error));
},
},
});
Although the functionality works fine, there are a few issues that need to be addressed:
- I am unable to capture issues in the component to display toast messages or handle error states.
- If I have multiple APIs, it will require writing numerous actions in the store.js file, which is not efficient. While creating a standard action that accepts HTTP method, URL etc. could be an option, I am unsure if this is a good practice.
What would be the best approach to overcome these challenges? How can I effectively monitor AJAX success or failure states within the component where the action is dispatched? What are the recommended practices for making API calls when utilizing Vuex?