I have a project underway that involves building an app using Vue.js, Vuex, and Firebase to update data from Firestore database to the state in mutations. Even though mutations are synchronous and promises (.then) are asynchronous, my current implementation seems to be working fine. However, I am unsure why it is still executing properly. Should I reconfigure mutations so that FB data is updated to the state without using a promise? Or could this setup be left as is? Below is the Vuex code for reference. Appreciate any insights!
import Vue from 'vue'
import Vuex from 'vuex'
import firebase from 'firebase'
import db from '@/firebase/init'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
items: null
},
getters: {
getItems: state => {
return state.items
}
},
mutations: {
setAllUser: state => {
const items = []
db.collection('users').get()
.then(snapshot => {
snapshot.forEach(doc => {
let userData = doc.data()
userData.id = doc.id
items.push(userData)
})
state.items = items
})
},
actions: {
setAllUser: context => {
context.commit('setAllUser')
}
}
})
**SOLUTION**
import Vue from 'vue'
import Vuex from 'vuex'
import firebase from 'firebase';
import db from '@/firebase/init'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
items: null
},
getters: {
getItems: state => {
return state.items
}
},
mutations: {
setAllUser: (state, items) => {
state.items = items
}
},
actions: {
setAllUser: async context => {
let snapshot = await db.collection('users').get();
const items =[]
snapshot.forEach(doc => {
let userData = doc.data()
userData.id = doc.id
items.push(userData)
})
context.commit('setAllUser', items)
}
}
})