简体   繁体   中英

Vuex action cannot commit mutation

I am working on an authentication function for a website, i am doing this with Firebase. Whenever the user logs into firebase my action in my store gets triggered and commits my mutation so the state gets set with the userID. Somehow whenever i try to commit my mutation i keep getting the error: commit is not defined . I can't seem to find a solution to this problem, all the forums i have been on havent helped so i really hope someone on here can help me with my problem, i would really appreciate it.

My action:

  async login({ dispatch }, user) {
    const token = await auth.currentUser.getIdToken(true);
    const idTokenResult = await auth.currentUser.getIdTokenResult();

    let approved = false;
    const userData = await firestore.collection('users').doc(user.email).get();
    if (userData) {
      approved = userData.data().isApproved
    }

    const userInfo = {
      name: user.displayname || null,
      email: user.email || null,
      avatar: user.photoURL || null,
      uid: user.uid,
      approved
    };
    Cookies.set('access_token', token); // saving token in cookie for server rendering
    commit('saveUID', userInfo.uid);
  }
};

My mutation:

saveUID (state, uid) {
    state.uid = uid;
}, 

The first parameter of the action is the context , which has functions like commit and dispatch . You extract ( destructuring assignment ) the dispatch by using { dispatch } as your parameter. You can use { dispatch, commit } to fix this and actually assign commit to a local variable.

destructuring assignment

async login({ dispatch, commit }, user) {
  commit('your_mutation')
}

using context

async login(context, user) {
  context.commit('your_mutation')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM