Get undefined of response.data from axios that stored in vuex

LI HO TAN

Get undefined of response.data console.log(this.$store.getters.getData)in vue component.

But, im able to get response.data using this statement console.log(resp.data)

I have tried console.log(data) in the success mutation, but it still returned undefined.

login.vue

    login: function() {
        let data = this.$store
          .dispatch("login", data)
          .then((resp) => {
            console.log(resp.data);  -> it returned data
            console.log(this.$store.getters.getData);  -> it returned undefined

            }
          })
          .catch(err => {});
      }

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import qs from 'qs'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    status: '',
    token: localStorage.getItem('token') || '',
    data: {},
  },
  mutations: {
    success(state, token, data) {
      state.status = 'success'
      state.token = token
      Vue.set(state, 'data', data)
    }
  },
  actions: {
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        axios.post(url, qs.stringify(data))
          .then(resp => {
            commit('success', resp.data.token, resp.data)
            resolve(resp)
          })
          .catch((error) => {
            commit('error')
            reject(error)
          })
      })
    },
  getters: {
    getData: state => state.data,
  }
})

console.log(resp.data); -> it returned data console.log(this.$store.getters.getData); -> it returned undefined

LI HO TAN

Finally, I figured out why it returned undefined because the mutation only accepts 2 parameters called state and payload, so other parameters will not be passed.

Reference - Can't send in a second parameter to the mutation in Vue store

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related