I recently switched from redux to VueX, and can't seem to get my initial state to update. I call an API from the backend in the created() hook of my main App component that returns data that initializes the state. I can see the network request along with the data, so I know that the action is being called, but it seems like either the mutation isn't being called or my mutation isn't working properly. I've tried debugging in the browser but for some reason chrome doesn't let me see any data when I add breakpoints. I have the Vue devtools extension installed and can't see anything other than the base state.
It's probably good to note that I'm using modules, and that the action I'm calling is tied to the top level/root level module. Here are the files that I think are relevant:
Main store
/* eslint-disable no-underscore-dangle */
import Vue from 'vue';
import Vuex from 'vuex';
import nandus from './nandus';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
nandus,
},
strict: process.env.NODE_ENV !== 'production',
});
export default store;
Nandus module
import axios from 'axios';
import { FETCH_NANDU_DATA, ASYNC_FETCH_NANDU_DATA } from '@/constants/nandus';
import modal from './modal';
import pdf from './pdf';
import scores from './scores';
import sections from './sections';
export default {
state: {
wushuStyles: null,
nanduFormTypes: null,
movements: null,
movementCodes: null,
nandu: null,
connections: null,
},
actions: {
[ASYNC_FETCH_NANDU_DATA]: ({ commit }) => {
function success(response) {
commit(FETCH_NANDU_DATA, response.data);
}
function failure(error) {
const message = error.response ? error.response.data.message : error.message;
console.error(`XHR Failed for getNanduData: ${message}`);
}
return axios.get('/api/nandu')
.then(success)
.catch(failure);
},
},
mutations: {
[FETCH_NANDU_DATA]: (state, data) => ({ ...state, ...data }),
},
modules: {
modal,
pdf,
scores,
sections,
},
};
App.vue
import { mapActions } from 'vuex';
import store from '@/store';
import { ASYNC_FETCH_NANDU_DATA } from '@/constants/nandus';
export default {
name: 'app',
computed: {
...mapActions([
ASYNC_FETCH_NANDU_DATA,
]),
},
created() {
store.dispatch(ASYNC_FETCH_NANDU_DATA);
},
};
Example data returned from API
{
wushuStyles: ['A', 'B'],
nanduFormTypes: ['A', 'B'],
movements: ['A', 'B'],
movementCodes: ['A', 'B'],
nandu: ['A', 'B'],
connections: ['A', 'B'],
}
In the mutation:
mutations: {
[FETCH_NANDU_DATA]: (state, data) => ({ ...state, ...data }),
},
A new object { ...state, ...data }
is being returned, but the state
is never mutated.
Changing the mutation to modify the state
should fix the issue:
mutations: {
[FETCH_NANDU_DATA]: (state, data) => {
// mutate state
state = { ...state, ...data }
},
},
As a side note, when doingVue.use(Vuex)
, an instance property $store
is added to all Vue instances. This means the store can be accessed within a Vue instance with this.$store
.
Example:
created() {
this.$store.dispatch(ASYNC_FETCH_NANDU_DATA);
},