I'm trying to implement pagination for my table. I have already implemented the "next" and "previous" buttons which work fine. The "previous" button is not displayed on the first page, only after which is correct. But the only issue I'm facing right now is when I'm on the last page, I don't want to display the "next" button. How do I implement this?
function App() {
const [apiData, setApiData] = useState([]);
const [searchQuery, setSearchQuery] = useState(); // Default = No search query
const [pageNumber, setPageNumber] = useState(1); //Default = Page 1
const [postsPerPage, setPostsPerPage] = useState(10); //Default 10 result per page
let apiQuery = "api";
useEffect(() => {
// All parameters are appended to this URL.
let apiQuery = "api";
// Add what page we are requesting to the API request.
apiQuery = apiQuery "&page=" pageNumber;
apiQuery = apiQuery "&pageSize=" postsPerPage;
console.log("posts: " , postsPerPage);
// Query data from API.
console.log("Querying: " apiQuery);
fetch(apiQuery)
.then((results) => results.json())
.then((data) => {
// Then add response to state.
setApiData(data);
});
}, [pageNumber, postsPerPage]); // Array containing which state changes that should re-reun useEffect()
const search=()=>{
// If searchQuery isn't empty add &search=searchQuery to the API request.
if (searchQuery) {
apiQuery = apiQuery "&search=" searchQuery;
}
// setting data as required, same as in the useEffect
fetch(apiQuery).then(result=>result.json()).then(data=>setApiData(data))
}
const totalPages = Math.ceil(apiData.length / postsPerPage);
return (
<div className="App">
<h1>Country lookup</h1>
<input value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
<button onClick={search}>Search</button>
<select value={postsPerPage} onChange={(event) => setPostsPerPage(event.target.value)}>
<option value={10}>10</option>
<option value={20}>20</option>
<option value={50}>50</option>
</select>
<Table apiData={apiData} />
These are the next and previous buttons I implemented. The whole code is in one file.
<nav>
{pageNumber!==1 && <button onClick={()=>setPageNumber(pageNumber-1)}>Previous page</button>}
{!apiData.length? pageNumber!== !apiData.length &&<button onClick={()=>setPageNumber(pageNumber 1)}>Next page</button>:""}
</nav>
</div>
);
}
CodePudding user response:
The condition you are looking for is:
{pageNumber < totalPages() && (<button>...</button>)}
You need to adjust your totalPages so that it will update once the api call is complete:
const [totalPage, setTotalPages] = useState(0);
useEffect(() => {
setTotalPages(Math.ceil(apiData.length / postsPerPage));
}, [apiData, postsPerPage]);
CodePudding user response:
Hope this code help
" maxNumberApiData = apiData.length "
{maxNumberApiData > 1 && pageNumber 1 <= maxNumberApiData ? (
<button onClick={() => setPageNumber(pageNumber 1)}>
Next page
</button>
) : (
""
)}