3
votes

Hi I've been trying to learn vuejs and vuex while trying to get response from an api call with vuex concept I got the following error.Please help. This error occurred
Error TypeError: Cannot read property 'dispatch' of undefined at app.js:12012

loginAction.js

export const getUsersList = function (store) {

    let url = '/Apis/allUsers';
    Vue.http.get(url).then((response) => {

            store.dispatch('GET_USER_RES', response.data);
        if (response.status == 200) {

        }
    }).catch((response) => {
        console.log('Error', response)
    })
}

loginStore.js

const state = {
    userResponse: []
}
const mutations = {
    GET_USER_RES (state, userResponse) {
        state.userResponse = userResponse;
    }
}
export default {
    state, mutations
}

login.vue

import {getUsersList} from './loginAction';
export default {

    created () {
        try{
            getUsersList();
        }catch(e){
            console.log(e);
        }
    },
    vuex: {
            getters: {
                getUsersList: state => state.userResponse
            },
            actions: {
                getUsersList
            }
    }
    }
    </ script>
1
Just checking to be sure, but there is an actions object as well? I can't imagine how you got to that error otherwise. vuex.vuejs.org/guide/actions.html#actions export default { state, mutations, actions } - ippi
Hi have u seen the script in login.vue there I have written action. Thank you for replying - UJ India

1 Answers

0
votes

If you call the actions manually (like in your try/catch) they'll not get the store context as the first argument. You could use getUsersList(this.store) I think, but instead I would use dispatch to reach all your actions. (I edited just a little bit to get a minimal running example, but I think you get the point!)

new Vue({
  render: h => h(App),
  created() {    
      this.$store.dispatch('getUsersList'); 
  },
  store: new Vuex.Store({
    getters: {
      getUsersList: state => state.userResponse
    },
    actions: {
      getUsersList
    }
  })
}).$mount("#app");

Also, use commit to reach the mutations instead of dispatch. ie:

export const getUsersList = function ({commit}) {
    let url = '/Apis/allUsers';
    Vue.http.get(url).then((response) => {
        commit('GET_USER_RES', response.data); // because GET_USER_RES is a mutation
        ...