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

Our express.js does not recognize GET requests from routers

When placeholders and predefined routes coexist in the same location, the predefined routes are never called if the placeholder was declared before them. For example: router.get("/:id", fetchEntry) router.get("/fancy-action/", doSomet ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

Utilizing Vue.js Datepicker to Specify a Date Range for Birth Date and Death Date

My goal is to disable all dates after today in both fields. Additionally, if a date of death is selected first, I want to disable all dates after that in the date of birth field. Here is what I have done so far: <Datepicker :disabled-dates="disabled ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Components in React are unable to be accessed

I'm a complete beginner when it comes to React and I'm facing issues with organizing my components into separate files. The error message I encounter is: ERROR in ./src/App.js 5:0-34 Module not found: Error: You attempted to import /components/ ...

`The process of adding an element to the beginning of an array``

I find myself in this scenario: I am dealing with 2 array1 variables, defined as array1 = ["fruit","vegetables"]; and array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"]) T ...

ReactJS: Error - Attempting to convert an undefined or null value to an object is not

Encountering an issue with my Beach component, which is throwing the following error: TypeError: Cannot convert undefined or null to object ResortDetail C:/Users/JS/Desktop/MERN/KR/frontend/src/screens/Beach.js:33 30 | <p>{description}< ...

Populating and dynamically sorting a v-select component in Vuetify

I am working on populating and sorting an array dynamically for use in a v-select component. However, I am encountering the es-lint warning 'unexpected side-effect in computed property' because I am modifying objects within that function call. Is ...

AngularFire - Structuring item references for child templates using ng-repeat

I have been struggling with this issue for hours and can't seem to find a solution. In my dashboard, all data from my Firebase database is visible using Ng-repeat. However, I am trying to select a specific item and view its details on another page. H ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Creating a specialized pathway with variable inputs within the URL

As a Node beginner, I am facing a challenge with an Express exercise on dynamic routes. The task at hand is to create a route that can accept dynamic arguments in the URL path and respond with a quote from the respective author. Here's a snippet of th ...

Conceal a div element after redirecting to a different HTML page

I have a dilemma with my two HTML pages - index.html and register.html. I am trying to navigate from index.html to register.html, but I want to skip the select region step and go straight to the login page. Here's the code snippet I've been attem ...

Tips for activating Vue.js production mode with webpack 2.7

I have encountered performance issues with Vue.js in my existing code base. Additionally, I noticed a notice in the browser console: So, I believe that one simple solution could be to switch Vue into production mode. Following the recommended link, I att ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased. Now, I'm curious about how to utilize the created/mounted lifecycl ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

The usage of ngRoute clashes with the functionality of Animated Scroll

I am experiencing a conflict between my ng-route and the animated scroll feature on my website: Below is the code for my scroll element: <a href="#one" class="goto-next scrolly">Next</a> In this code, "#one" represents the section ID to scro ...