[Vuejs]-Vuex state not setting to getter

4đź‘Ť

âś…

The first argument in an action is the Vuex context. You’ve named it state and tried to access state.users from it, so I believe you’re incorrectly assuming it’s the Vuex state. Note users does not exist in the context, so it would be undefined, and users['GOOGLE_DRIVE'] would then lead to the error you observed:

const actions = {
  async login(state, payload) {
              ^^^^^ ❌ arg1 is context, not state
    â‹®
    state.users[payload] = user  // ❌ state.users is undefined
  }
}

However in Vuex 3, actions should not be mutating state directly. That should be moved into a Vuex mutation:

const mutations = {
  'SET_USERS'(state, users) {
    state.users = { ...state.users, ...users }
  }
}

Then the action could invoke the mutation through the context’s commit():

const actions = {
  async login({ commit }, payload) {
    â‹®
    commit('SET_USERS', { GOOGLE_DRIVE: user })
  }
}

Finally, your getter is not declared correctly. The arguments and the state assignment within it make your getter look like a mutation. To fix the getter:

  1. Getters receive state as its 1st argument and any other getters as the 2nd argument, so remove the other arguments.
  2. It needs to return something, typically based on its state argument (e.g., the users getter should return state.users).
  3. Getters should not mutate the Vuex state, so remove the state.users assignment.

The getter should look like this:

const getters = {
  users: state => state.users,
}

demo

👤tony19

Leave a comment