Reputation: 881
I am getting the data from firebase and storing them in Vuex state. I am showing them in a list format using v-for in characters component. When the page loads for the first time the list of characters is showing perfectly but when I am navigation to other pages and coming back to characters again the list showing duplicate values.
<ul class="characters-list">
<li v-for="allHero in getAllHeros" v-bind:key="allHero.id">
<router-link :to="{name: 'characterDetail', params: {id: allHero.id}}">
<div class="hero-thumbnail">
<img :src="allHero.imageUrl" :alt="" />
</div>
<div class="hero-title">
<h3>{{ allHero.name }}</h3>
</div>
</router-link>
</li>
</ul>
computed: {
...mapGetters([
"getAllHeros"
]),
}
methods: {
...mapActions(["fetchAllHeros"])
},
created() {
this.fetchAllHeros();
}
const state = {
allHeros: [],
}
const getters = {
getAllHeros: (state) => {
return state.allHeros
},
}
const actions = {
fetchAllHeros: ({commit}) => {
database.collection('heros').get()
.then(snapshot => {
snapshot.forEach(doc => {
let heros = doc.data();
heros.id = doc.id
//console.log(heros);
commit('setAllHeros', heros)
})
})
}
}
const mutations = {
setAllHeros: (state, payload) => {
state.allHeros.push(payload);
}
}
Upvotes: 0
Views: 735
Reputation: 505
i too wasted much time figuring out this, finally i did like this,
feed:[],feedInitialLoad:false,
computed:{...mapState(['feedInitialLoad'])},
created(){
if(!this.feedInitialLoad){
//first time visit
this.loadFeed();
//mutate the feedInitialLoad to true
}
}
Upvotes: 0
Reputation: 1768
Perform a check to see if allHeros
exists or not.
You could put this in created()
or even in fetchAllHeros
. if you put it in the action, then be sure to pass in getters
along with commit
.
created() {
if (this.getAllHeros.length < 1) {
this.fetchAllHeros();
}
}
fetchAllHeros: ({commit, getters}) => {
if (getters.getAllHeros.length > 0) {
return;
}
// Keep the code you already have
database.collection('heros').get()
...
}
Upvotes: 1