I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the pagination is detecting page 0 instead of the first page where events should be displayed. Can someone please guide me on what I'm doing wrong? Any help in resolving this would be greatly appreciated.
index.js
state: {
limit: 12,
page: 0,
events: [],
},
mutations: {
limit(state, limit) {
state.limit = limit
},
page(state, page) {
state.page = page
},
allEvents(state, allEvents) {
state.events = allEvents;
},
},
actions: {
async fetchEvents({ commit, state }) {
try {
const response = await provider().clients.graphqlClientPortal.query({
query: gql`
query LiveEvents($limit: Int!, $page: Int!){
liveEvents(pagination:{limit:$limit, page:$page}, order:{startsAt:{direction: DESC}}){
total,
data{
id,
name,
stub,
description,
mainImage{
id,
uri
},
location,
type,
layout
chat,
liveStream{
endsAt,
startsAt
}
}
}
}
`,
variables: {
limit: state.limit,
page: state.page
},
});
console.log(response.data)
commit('allEvents', response.data.liveEvents.data);
commit("limit", response.data.liveEvents.data.limit),
commit("page", response.data.liveEvents.page)
//commit("total", response.data.liveEvents.total)
} catch (error) {
console.log('error-message', error.graphQLErrors)
}
},
}
List.vue
<template>
// displaying events
<div v-for="(event, index) in displayedPosts" :key="index">
<h2>{{ event.name }}</h2>
<p>{{ event.location }}</p>
...
</div>
// pagination with buttons and numbers
<div>
<ul>
<li>
<button type="button" v-if="page != 1" @click="page--"> Previous </button>
</li>
<li>
<button type="button" v-for="pageNumber in pages.slice(page - 1, page + 5)" :key="pageNumber"
@click="page = pageNumber"> {{ pageNumber }} </button>
</li>
<li>
<button type="button" @click="page++" v-if="page < pages.length"> Next </button>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "List",
data() {
return {
posts: [],
page: this.$store.state.page,
perPage: this.$store.state.limit,
pages: [],
}
},
mounted() {
this.$store.dispatch("fetchEvents")
},
methods: {
getPosts() {
let events = this.$store.state.events;
for (let i = 0; i < events.length; i++) {
this.posts.push(events[i])
}
},
setPages() {
let numberOfPages = Math.ceil(this.posts.length / this.perPage);
for (let index = 1; index <= numberOfPages; index++) {
this.pages.push(index);
}
},
paginate(posts) {
let page = this.page;
let perPage = this.perPage;
let from = (page * perPage) - perPage;
let to = (page * perPage);
return posts.slice(from, to);
}
},
computed: {
displayedPosts() {
return this.paginate(this.posts);
}
},
watch: {
posts() {
this.setPages();
}
},
created() {
this.getPosts();
},
filters: {
trimWords(value) {
return value.split(" ").splice(0, 20).join(" ") + '...';
}
}
}
</script>