Reputation:
I am a beginner to REACT and I am trying to figure out how to implement pagination into my React project using axios. The api I am using (swapi.dev) has a total of 87 characters, when you submit a GET request with https://swapi.dev/api/people you only get 10 characters per page, but to can use the link in postman, which says "next" to switch between each pages of characters. I am trying to make an request with axios to paginate each list of 10. I figured a for loop would be good to use but I am not sure.
import React, { useEffect, useState } from "react";
import axios from "axios";
import _ from "lodash";
import ReactPaginate from "react-paginate";
import Table from "react-bootstrap/Table";
export default function Posts() {
const [characterData, setCharacterData] = useState([]);
//use a for loop to loop through all sites
useEffect(() => {
axios
.get("https://swapi.dev/api/people/")
.then((res) => {
console.log(res.data.next);
setCharacterData(res.data.results);
})
.catch((err) => {
console.log(err);
});
}, []);
// for ( i = 0; i < data.results.length, i++) {
// names = names + data.results[i].name
// }
// function handleclick(e) => {
// }
return (
<>
<Table stripped bordered hover className="project--table">
<thead>
<tr>
<th>Name</th>
<th>Birth Year</th>
<th>Height</th>
<th>Mass</th>
<th>Homeworld</th>
<th>Species</th>
</tr>
</thead>
<tbody>
{characterData.map((character, index) => {
return (
<tr key={index}>
<td>{character.name}</td>
<td>{character.birth_year}</td>
<td>{character.height}</td>
<td>{character.mass}</td>
<td>{character.homeworld}</td>
<td>{character.species}</td>
</tr>
);
})}
</tbody>
</Table>
{/* <button onClick={}>Next</button> */}
</>
);
Upvotes: 0
Views: 703
Reputation: 456
I checked your api and the next key have a value that contains the url for the next page. No need for a loop you can just check if the next key exists and depending on that you send a request. you can create a new state that will contain the next uri and on the onClick function you check if for the "next" key. it's something like this :
const [next,setNext]= useState("");
in the useEffect you wrote you can add :
axios
.get("https://swapi.dev/api/people/")
.then((res) => {
console.log(res.data.next);
setCharacterData(res.data.results);
if (res.data.next) setNext(res.data.next);
})
and finally in the onClick function :
if(next) {
axios.get(next).then(res=> setCharacterData(res.data.results))
}
I think there is a better solution for this but you can work with this atm.
Upvotes: 1