0

I am receiving 50 data with get request using axios, and I want to add pagination to my code on every page i want 5 results, how to implement pagination with axios response.

    import React from 'react';
    import axios from 'axios';

    export default class PersonList extends React.Component {
      state = {
        persons: []
      }

      componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/Todos`)
          .then(res => {
            const persons = res.data;
            this.setState({ persons });
          })
      }

      render() {
        return (
         <div>
          <ul>
            { this.state.persons.map(person => <li>{person.name}</li>)}
          </ul>
                   <button onClick={this.previousPage}>PreviousPage</button>
                   <button onClick={this.nextPage}>Next Page</button>
        </div>
        )
      }
    }
Supriya Bhart
  • 89
  • 1
  • 3
  • 10
  • Possible duplicate of [Paginate Javascript array](https://stackoverflow.com/questions/42761068/paginate-javascript-array) – Alexander Staroselsky Sep 27 '18 at 16:23
  • 1
    This isn't about React and Axios, you are asking about paginating a JavaScript array. What properties do you think you'd need to store and manipulate in state to achieve this? What Array.prototype methods such as `slice()` could you use to take a certain portion of the `persons` for each `page` taking account some kind of page `size`? – Alexander Staroselsky Sep 27 '18 at 16:26
  • ha can you please help – Supriya Bhart Sep 27 '18 at 17:34

1 Answers1

4

Here is a simple example using library paginate-array to paginate array items stored in the component's state. If you inspect the source for paginate-array, you'd see the logic for creating a "page" is fairly straightforward, so you may be able to use it for inspiration for your own pagination utilities. This example uses Todos from JSONPlaceholder, but you can modify the example as needed. Keep in mind the endpoint https://jsonplaceholder.typicode.com/todos does not have objects with property name as your example suggests. This example does simple checks for page numbers with the click handlers for the previous/next buttons to help ensure invalid pages cannot be selected. This example is assuming you plan to load all the data on the component loading, rather than requesting new pages of data via axios/fetch.

import React, { Component } from 'react';
import paginate from 'paginate-array';

class TodoList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todos: [],
      size: 5,
      page: 1,
      currPage: null
    }

    this.previousPage = this.previousPage.bind(this);
    this.nextPage = this.nextPage.bind(this);
  }

  componentDidMount() {
    fetch(`https://jsonplaceholder.typicode.com/todos`)
      .then(response => response.json())
      .then(todos => {
        const { page, size } = this.state;

        const currPage = paginate(todos, page, size);

        this.setState({
          ...this.state,
          todos,
          currPage
        });
      });
  }

  previousPage() {
    const { currPage, page, size, todos } = this.state;

    if (page > 1) {
      const newPage = page - 1;
      const newCurrPage = paginate(todos, newPage, size);

      this.setState({
        ...this.state,
        page: newPage,
        currPage: newCurrPage
      });
    }
  }

  nextPage() {
    const { currPage, page, size, todos } = this.state;

    if (page < currPage.totalPages) {
      const newPage = page + 1;
      const newCurrPage = paginate(todos, newPage, size);
      this.setState({ ...this.state, page: newPage, currPage: newCurrPage });
    }
  }

  render() {
    const { page, size, currPage } = this.state;

    return (
      <div>
        <div>page: {page}</div>
        <div>size: {size}</div>
        {currPage &&
          <ul>
            {currPage.data.map(todo => <li key={todo.id}>{todo.title}</li>)}
          </ul>
        }
        <button onClick={this.previousPage}>Previous Page</button>
        <button onClick={this.nextPage}>Next Page</button>
      </div>
    )
  }
}

export default TodoList;

Here is a basic example in action. The example also has an approach to handling a changeable size dropdown.

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91