How To Paginate JSON data (Javascript array) returned from my Axios callback function using react-paginate?

161 Views Asked by At

I have written a ReactJS program that returns JSON array data from an Axios call to my Springboot Rest backend but now I want to paginate the returned rows of data using react-pagination. I have successfully imported the react-pagination example into my program but I am unable to set the "items" Javascript array (at the moment hardcoded as const items = [1, 2, 3, 4, 5];) which the react-pagination function uses as its data to paginate, to use the response data actually returned by my Axios function call (so at the moment the pagination is only working on hardcoded set data for "items" instead of setting "items" to the JSON response data and paginating that).

Here is my code:

import ReactPaginate from 'react-paginate';
import * as ReactDOM from 'react-dom';
import React, { useEffect, useState } from "react";
import axios, {isCancel, AxiosError} from 'axios';


var myJson = null;

var items = null;




function Main() {

  //const [items, setItems] = useState(null);

  
  const [result, setResult] = useState(null);




  axios.get('http://localhost:8080/otp/getData/' + type + "/" + id)
    .then(function (response) {
      // handle success
      console.log(response);
       myJson = JSON.parse(JSON.stringify(response.data));       
//testing that the slice() function works
//var myJson = JSON.parse(JSON.stringify(response.data)).slice(1,2);

    });




function Items({ currentItems }) {
  return (
    <div className="items">
    {currentItems && currentItems.map((item) => (
      <div>
        <h3>Item #{item}</h3>
      </div>
    ))}
      </div>
  );
}




  function PaginatedItems({itemsPerPage }) {

  //const [items, setItems] = useState(null);

  axios.get('http://localhost:8080/otp/getData/CHECKER/12345678')
  .then(function (response) {
    myJson = JSON.parse(JSON.stringify(response.data));
     //setItems(myJson); //DOESN'T WORK
    //items = myJson; //DOESN'T WORK
  });




  // I WANT TO REPLACE THIS HARDCODED items ARRAY BELOW WITH
  //  THE JSON DATA RETURNED BY MY AXIOS FUNCTION ABOVE
  // (something like items = myJson; )

   items = [1, 2, 3, 4, 5];
 


  // We start with an empty list of items.
  const [currentItems, setCurrentItems] = useState(null);
  const [pageCount, setPageCount] = useState(0);
  // Here we use item offsets; we could also use page offsets
  // following the API or data you're working with.
  const [itemOffset, setItemOffset] = useState(0);


  
  useEffect(() => {
    // Fetch items from another resources
    // - DO I PUT THE AXIOS CALL HERE AND USE setCurrentItems(myJson.first_key_value) ?
    const endOffset = itemOffset + itemsPerPage;
    console.log(`Loading items from ${itemOffset} to ${endOffset}`);
    setCurrentItems(items.slice(itemOffset, endOffset));
    setPageCount(Math.ceil(items.length / itemsPerPage));
  }, [itemOffset, itemsPerPage]);



  // Invoke when user click to request another page.
  const handlePageClick = (event) => {
    const newOffset = event.selected * itemsPerPage % items.length;
    console.log(`User requested page number ${event.selected}, which is offset ${newOffset}`);
    setItemOffset(newOffset);
  };

  
  return (
    <>
      <Items currentItems={currentItems} />
      <ReactPaginate
        nextLabel="next >"
        onPageChange={handlePageClick}
        pageRangeDisplayed={3}
        marginPagesDisplayed={2}
        pageCount={pageCount}
        previousLabel="< previous"
        pageClassName="page-item"
        pageLinkClassName="page-link"
        previousClassName="page-item"
        previousLinkClassName="page-link"
        nextClassName="page-item"
        nextLinkClassName="page-link"
        breakLabel="..."
        breakClassName="page-item"
        breakLinkClassName="page-link"
        containerClassName="pagination"
        activeClassName="active"
        renderOnZeroPageCount={null}
      />
    </>
  );

}



return (

<div id = 'myApp' style={{margin: "10px"}}>

    
<PaginatedItems itemsPerPage={1} />


</div>  
     
);


}

export default Main;

Please can you help me to assign the items array to the response data returned by my Axios call so that my react pagination can work correctly, thanks!

0

There are 0 best solutions below