Search code examples
vue.jsvuexvue-resource

Cannot read property 'post' of undefined in store.js


I have an action in store.js - vuex called signUserIn. SignUserIn method is just a http post request. I have imported Vue-Resource in store file: import VueResource from 'vue-resource', Vue.use(VueResource) and also in main.js - store.js has been imported. In my SignIn.vue component I dispatch SignIn action. I get back an error: Cannot read property 'post' of undefined. What is wrong with my imports or code?

action:

signUserIn ({commit, getters}, payload) {
      let data = {
        _email: payload.email,
        _password: payload.password
      }
      let that = this
      that.$http.post(
        'url',
          data,
        { channel: 'default' },
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
      ).then(response => {
          const newUser = {
            email: payload.email,
            login: payload.login,
            cart: []
          }
          commit('setUser', newUser)
      }, error => {
          console.error(error);
      });
    }

Mutation:

setUser (state, payload) {
    state.user = payload;
}

Solution

  • $http is property of Vue instance, in vuex store you should import Vue and use Vue.http to make requests.

    Vue.http.post(
        'url',
          data,
        { channel: 'default' },
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
      )
    ...