[Vuejs]-How to write Vuex mutation without asynchronous promise

4👍

Move your async code to actions:

{
  mutations: {
    setAllUser: (state, items) => state.items = items
  },
  actions: {
    setAllUser: async context => {
      let snapshot = await db.collection('users').get();
      let items = snapshot.map(doc => {
        let userData = doc.data();
        userData.id = doc.id
        return userData;
      });
      context.commit('setAllUser', items)
    }
}

So for the question why?

  • Single responsibility: your mutation should only be responsible for setting the state.
  • Not sure how would vue-devtools react, I guess it will just show you a single mutation.
  • Your mutation should only depend on payload and state, not on the network/server response etc
  • Your colleagues won’t expect this to happen

Why it works?

  • The same reason it works if you just do this directly from devtools: window.store.state.items = []. Vuex just overrides getters and updating the state fires updating the dom.

P.S. You can use promise.then inside your action instead of await.

Leave a comment