I'm adding pagination for the list of items I get through GraphQl query. I've managed to get everything sorted however for the past day one single state has decided to bug me.
I use start and limit as query options to paginate. Let's say the limit of items is always 5
On component mount I set initial values:
useEffect(() => {
setPartStart(0)
setPartLimit(5)
setCurrentPage(1)
},[])
Now, when I get a total count of parts through different query, I'm calling a following function:
const calculatePages = () => {
setPages([])
let rawNumOfPages = numberOfParts.partsCount / partLimit
let roundedNumOfPages = Math.ceil(rawNumOfPages)
setNumOfPages(roundedNumOfPages)
for(let page = 1; page <= roundedNumOfPages; page++) {
setPages(prevState => [...prevState, <button key={page} value={page} className={`${currentPage === page ? 'active' : 'pagination--box'}`} onClick={(e) => {selectPage(e)}}>{page}</button>])
}
}
It is calculating a total number of pages from the total count of parts and the selected limit. Then in the for loop I'm outputting a button element for each page for navigation purposes. Then I output that navigation array of buttons as {pages} in a div
The issue is when I call selectPage function from onClick in button element:
const selectPage = (e) => {
let actualPage = parseInt(e.target.value)
if(actualPage > currentPage) {
setPartStart(prevState => parseInt(prevState + partLimit))
setCurrentPage(actualPage)
console.log(currentPage)
} else if(actualPage < currentPage) {
setPartStart(prevState => prevState - partLimit)
setCurrentPage(actualPage)
console.log(currentPage)
}
}
Here I'm getting a number of page that has been clicked through e.target.value and then compare it to the currentPage, if the new one is bigger then I set start value for GraphQl query to prevState + limit, if the new one is lower then I set start value to be prevState - limit.
The issue is that the currentPage is always 1, even though in DevTools it is changing when I look at Components explorer. These console.logs always put out 1. Due to async nature of useState I would expect that the currentPage updates to 2 when I click on 3 but it doesn't, it stays on 1 in these console logs (there is also a condition to add class active to the button if the currentPage === Page but that too stays always on 1). Correct state in the DevTools hooks sidebar only puzzled me more.
Any help is welcomed, Thanks