Reputation: 127
I have a problem with re-render my table
component when data in my store
is updated,
I have a simply table with v-for
like below:
<tr v-for="d in getDatas" v-bind:key="d.id">
and buttons to change page:
<button class="fa fa-chevron-left" @click="previousPage"/>
<button class="fa fa-chevron-right" @click="nextPage"/>
I load data to my datas before i open my component where is this table, and i get this data from store like below:
computed: {
getDatas () {
return this.$store.getters.getDatas;
}
},
but how to update my store with data
when i click on button nextPage
or previousPage
?
here is my methods:
methods: {
...mapActions(["fetchDatas"]), //this is my action
nextPage() {
this.currentPage += 1;
},
previousPage() {
if(this.currentPage != 1) {
this.currentPage -= 1;
}
},
and my action:
async fetchDatas({ commit },{ currentPage}) {
const data = await fetch(`someURL&perPage=${currentPage}`);
const response = await data.json();
commit('setData', response);
}
so, how to reload component and my store when i click on my next/previousPage
?
Upvotes: 0
Views: 1423
Reputation: 2616
You already have a computed
property that automatically updates when your store updates. All you have to do is trigger the action in your methods for changing pages.
nextPage() {
this.currentPage += 1;
this.fetchDatas(this.currentPage);
},
previousPage() {
if(this.currentPage != 1) {
this.currentPage -= 1;
this.fetchDatas(this.currentPage);
}
},
And unless you have a compelling reason for requiring an Object parameter to the action, I would remove the curly braces entirely:
async fetchDatas({ commit }, currentPage) {
...
Otherwise you need to call it with this.fetchData({currentPage: this.currentPage})
.
Upvotes: 2
Reputation: 57
You can setup a watch on the currentPagevariable where the getDatas action would be fired again on the change of the current page after clicking the buttons.
A watch can be declared as so:
watch: {
currentPage: function (newValue) {
this.$store.dispatch('fetchDatas', this.currentPage)
},
}
Upvotes: 1