What are the reasons behind the pagination with numbers not functioning properly in Vue?

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>

Answer №1

  1. It seems like there are a few issues with how you are handling the data in your Vuex store. Specifically, the page and limit variables are not being updated correctly. Make sure to commit the mutation with the right data and remember that these variables are not part of the liveEvents.data object.

  2. Your component is not set up to watch for changes in the events state in the Vuex store. This means that when the events state changes, your component does not react accordingly.

  3. Another issue lies in how you are initializing and updating the posts data. It's important to ensure that Vue can track changes to this data by setting it up reactively.

To address these issues, consider implementing the following solutions:

  1. Make sure to update the fetchEvents action in your Vuex store to commit the correct limit and page values:
actions: {
  async fetchEvents({ commit, state }) {
    // ...
    commit('allEvents', response.data.liveEvents.data);
    commit("limit", state.limit),
    commit("page", state.page)
    // ...
  },
}
  1. Set up a watcher in your component to monitor changes in the events state and update posts accordingly:
watch: {
  '$store.state.events': {
    handler: function(events) {
      this.posts = events;
    },
    immediate: true,
  },
  posts() {
    this.setPages();
  }
},
  1. Remove unnecessary methods like getPosts and lifecycle hooks if they are no longer required.

  2. Ensure that page is initialized to 1 instead of 0 in your Vuex store:

state: {
  limit: 12,
  page: 1,
  events: [],
},
  1. Adjust the paginate method to handle the scenario where page equals 0:
paginate(posts) {
  let page = this.page;
  let perPage = this.perPage;
  let from = (page * perPage) - perPage;
  let to = (page * perPage);
  return page > 0 ? posts.slice(from, to) : [];
}
  1. Modify the v-if condition in the Previous button to account for cases where page is greater than 1:
<button type="button" v-if="page > 1" @click="page--"> Previous </button>

By making these adjustments, your pagination functionality should work as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

Show only the populated fields in a user profile with ReactJS

Purpose Showcasing only completed fields. Context In my app, users fill out an application with fields like "early reg fee, early reg date, regular reg fee, regular reg date". After completing all the information and clicking "view profile", they should ...

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

Running a PHP function within a PHP environment

After the user clicks the submit button and no errors are present, a token value input is generated in the script below. The goal is to post this value inside a php page for use in a query. While the input value is successfully generated, posting it to the ...

output an array based on a specified key/value relationship

Looking to filter results based on a key/value pair in an array? Consider this example array: .factory('dishesFactory', function (){ var factory = { dishes :[ {nameEnglish: 'TAPENADE', nameLocal: 'Tapenade', descript ...

Utilizing $.each to dynamically add data to a jQuery Mobile listview

Trying to implement a data reading mechanism using ajax resulted in unexpected html tag generation for <ul> <li>. The code snippet is as follows: (function( $, undefined ) { $(document).on("pagecreate", ".jqm-demos", function(){ ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

Exploring the Possibilities of Socket.io Integration with Express 4 Across Multiple Pages: Dive Into Socket.io Sample Code

Just to clarify, I came across a similar question on Stack Overflow before posting this. However, the answer there was not clear to me and my query is slightly different. Thus, I am hoping for a more straightforward explanation. The Express Generator sets ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Gulp is failing to convert SCSS files into CSS

I'm having trouble getting gulp to compile my SASS code into CSS automatically. What could be the issue? file structure: public -css --styles.css -index.html sass -styles.scss gulpfile.js package.json Gulpfile: var gulp = require('gulp') ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

Utilize Mongo's $facet feature to retrieve and calculate the number of tags associated with the products that have been

My current aggregation pipeline looks like this: aggregate.lookup({ from: 'tags', localField: 'tags', foreignField: '_id', as: 'tags' }); aggregate.match({ productType: 'prod ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Strategies for Applying Filters in Search Feature on IOS Devices

Currently, I have an array of books that are being displayed on my view. At the top of the view, there are 3 filters available: (All | Reading level 1 | Reading Level 2 | Reading Level 3) (All | Informational | Literature) (All | Published in 2000-2005 | ...

having difficulty showing the column filter feature in the DataTable

I am currently utilizing a datatable and in need of an individual column-based search feature along with a global search. I am working with a 2D array. The search boxes are being displayed, however, the search functionality is not functioning correctly fo ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Utilizing Django in conjunction with Vue to identify and address form validation errors

Utilizing a Django ModelForm with crispy forms for display on the template, upon completion of filling out the fields and clicking Submit, an email is triggered in the backend using Django's send_email functionality. However, the issue arises from th ...