Leff
Leff

Reputation: 1276

Vue/ Vuex - not saving state data

I have made a vuex module to keep the user state of the data. It looks like this:

import Vue from "vue";

export default {
  namespaced: true,
  state: {
    data: {},
    meta: {}
  },
  mutations: {
    setInitialUserData: function(user){
      state.data = user;
    },
    setUserMeta: function(meta){
      state.meta = meta;
    },
  },
  actions: {
    setInitialData: function({commit}, user){
      console.log(user);
      commit('setInitialUserData', user.user);
      commit('setUserMeta', user.userMeta);
    },
  },
  getters: {
    getUser: (state) => state.data,
    getUserMeta: (state) => state.meta
  }
}

I am trying to save the data on login in my component like this:

this.$backend.post('/user/login', null, payload)
      .then(response => {
        this.$store.dispatch('auth/login', response.data.token);
        this.$store.dispatch('user/setInitialData', response.data.user);
        //this.$router.push('intranet');
      })
      .catch(error => {
        //console.log(error);
      });
  }

The data that I get here:

setInitialData: function({commit}, user){
      console.log(user);
      commit('setInitialUserData', user.user);
      commit('setUserMeta', user.userMeta);
    },
  }, 

Looks like this:

    "user": {
        "name": "John Doe",
        "nice_name": "John",
        "login_name": "John",
        "email": "[email protected]"
    },
    "userMeta": {
        "department": "Administrasjon",
        "region": "Oslo",
        "industry": "Bane"
    },

But, nothing gets saved to state, on inspecting the vuex state, I get empty objects for both user data and user meta:

user:Object
data:Object (empty)
meta:Object (empty)

Upvotes: 0

Views: 3520

Answers (1)

Wouter Vandevelde
Wouter Vandevelde

Reputation: 904

You are not passing the state to your mutators:

mutations: {
    setInitialUserData: function(state, user){
         state.data = user;
    },
    setUserMeta: function(state, meta){
        state.meta = meta;
    },
},

Upvotes: 4

Related Questions