Currently, I am facing an issue with my vuex store. I have implemented two different actions in my store, one being reactive and the other not. However, I specifically need the loadSlidesEach()
action to be reactive so that the data gets updated accordingly. Despite my efforts, I am unable to pinpoint the mistake.
Below is a snippet of my store:
const store = new Vuex.Store({
state: {
loadedSlides: []
},
mutations: {
setSlides(state, slides) {
state.loadedSlides = slides
},
setSlidesPush(state, slide) {
state.loadedSlides.push(slide)
}
},
getters: {
loadedSlides(state) {
return state.loadedSlides
}
},
actions: {
loadSlides({ commit, getters, state }) {
firebase.database().ref('/slides/').on('value', snapshot => {
const slidesArray = []
const obj = snapshot.val()
for (const key in obj) {
slidesArray.push({ ...obj[key], id: key })
}
commit('setSlides', slidesArray)
})
},
loadSlidesEach({ commit, getters, state }, id) {
firebase.database().ref('/slides/' + id).on('value', snapshot => {
const slide = snapshot.val()
commit('setSlidesPush', { ...slide })
})
}
}
})
Component 1: Array from slides() reacts as expected
export default {
computed: {
slides() {
return this.$store.getters.loadedSlides
}
},
created() {
this.$store.dispatch('loadSlides')
}
}
Component 2: Array from slides() is not reactive
export default {
computed: {
slides() {
return this.$store.getters.loadedSlides
}
},
created() {
const slides = ['1','2','3']
for (let i = 0; i < slides.length; i++) {
this.$store.dispatch('loadSlidesEach', slides[i])
}
}
}
I suspect that the issue might lie within the initial state or the mutation using push(). Any advice or suggestions?
Update: Upon further investigation, I noticed that the difference between the two actions lies in the mutations. What would be the best approach to setting the state in vuex? Calling the action loadSlidesEach() in a loop seems to confuse the store. Thoughts?