Having trouble implementing pagination for news-api in Vue.js2?

I am currently working on implementing a basic pagination feature in my Vue component specifically for the newsapi.org API.

While my initial API call in the created hook is functioning as expected, I am encountering difficulties navigating to different pages.

Although I am aware of existing reusable pagination components like Vuetify which I am incorporating in my project, I opted to manually create a simple pagination system within my component. This includes two buttons for moving to the next and previous pages, along with a button in the middle displaying the current page number.

Below is the Vuetify code snippet for the pagination...

<div class="text-xs-center">
        <v-btn fab small dark color="teal" :disabled="disabled" @click.prevent="prev()">
          <v-icon dark>mdi-chevron-left</v-icon>
        </v-btn>
        <v-btn outline fab class="title" color="white">{{ this.currentPage }}</v-btn>
        <v-btn fab small dark color="teal" @click.prevent="next()">
          <v-icon dark>mdi-chevron-right</v-icon>
        </v-btn>
      </div>

Additionally, here is my code for fetching results and managing page changes...

computed: {
    pageCount() {
      return Math.ceil(this.totalResults / this.maxPerPage);
    },
created() {
    this.fetchNews();
  },
  methods: {
    fetchNews() {
      axios
        .get(this.apiUrl)
        .then(res => {
          this.articles = res.data.articles;
          this.totalResults = res.data.totalResults;
          console.log(res.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    next() {
      this.currentPage += 1;
      this.fetchNews();
    },
    prev() {
      this.currentPage -= 1;
      this.fetchNews();
    },

To retrieve 9 results per page, I have set the page size to 9. The following is how I constructed the apiUrl...

apiUrl: `https://newsapi.org/v2/everything?q=real-madrid&language=en&page=${this.currentPage}&pageSize=9&apiKey=5b***********8f4aa3d63cf050b2`,

I am unsure whether I need to leverage the pageCount variable to accomplish my goal. Any advice or assistance would be greatly appreciated.

Answer №1

In order to optimize performance, it is recommended to turn the 'apiUrl' into a computed property.

data() {
  return {
    currentPage: 1
    maxPerPage: 9,
    totalResults: 0,
  }
},
computed: {
  pageCount() {
    return Math.ceil(this.totalResults / this.maxPerPage);
  },
  isFirstPage() {
    return this.currentPage === 1
  },
  isLastPage() {
    return this.currentPage >= this.pageCount
  },
  apiUrl() {
    return `https://newsapi.org/v2/everything?q=real-madrid&language=en&page=${this.currentPage}&pageSize=${this.maxPerPage}&apiKey=5b***********8f4aa3d63cf050b2`
  },
}
methods: {
    fetchNews() {
      axios
        .get(this.apiUrl)
        .then(res => {
          this.articles = res.data.articles;
          this.totalResults = res.data.totalResults;
          console.log(res.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    next() {
      if (this.isLastPage) return
      this.currentPage += 1;
      this.fetchNews();
    },
    prev() {
      if (this.isFirstPage) return
      this.currentPage -= 1;
      this.fetchNews();
    },
},

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

Creating a smooth JQUERY fade slideshow with seamless transitions, no white gaps in

I am having trouble with the slideshow on my Wordpress website www.2eenheid.de. I want the images to fade smoothly between each other instead of fading into a white background color first and then into the next image. Can anyone help me find a solution for ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Apply the child's style if the parent's sibling contains the specified class

I am struggling to add the class "bold" to a child element (span) of a parent element (button.usa-nav-link). This parent element has a sibling (ul li.active) with the class .active. When the sibling is active, I want the child element's text to be bol ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Utilizing Font Awesome icons dynamically presents challenges when integrating with SVG & JavaScript

Recently, I started using the new JS&SVG implementation of font-awesome's v5 icons. It seems to be working perfectly for icons (such as <i class='fas fa-home'></i>) that are already present in the DOM at page load. The <i& ...

Having issues with django-autocomplete-light triggering JavaScript errors

My implementation of django-autocomplete-light is causing some issues with rendering autocomplete options. There is a section on the website where it functions perfectly, but in another section, it only works partially. The autocomplete options display c ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

What is the best way to synchronize HTML5 audio playback on different browsers?

When working with audio files in different browsers like Chrome, Firefox, and Safari, I noticed that they seem to start at slightly different timestamps. This discrepancy becomes more pronounced as the audio progresses, with a gap of around 5 seconds after ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus. Upon receiving the event, I trigger a method that fetches data using a Swagger client. The goal is ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Despite my attempts to force a repaint, the progress bar remained static during intensive tasks

My JavaScript method works fine in Chrome, taking about 2000 ms to iterate over ~200 inputs, insert values, and trigger onchange events. However, it's a different story in IE where it takes about 10000 ms. To show the progress of this process, I deci ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Importing pixi-sound in the right way for PIXI JS

I have a question regarding the proper way to import pixi-sound into my project. I am facing an issue with the following code snippet: import * as PIXI from "pixi.js"; import PIXI_SOUND from "pixi-sound"; const EFFECT_SOUNDS = [...list of music] for (le ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

Utilize useEffect to dynamically populate several dropdown menus with data

I am currently implementing a method to populate two dropdowns in my component using useEffects. function fetch_data_for_dropdown1() { return axios.get("http://127.0.0.1:5001/dropdownonedata"); } function fetch_data_for_dropdown2() { return axios ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...