Reputation: 257
I've developed a page where it has a simple search function and pagination. Both the search function and pagination were working well so far, but I've found out that if I tried searching from any pages other than the 1st page
(e.g. 2nd or 3rd page), the search won't work properly anymore, I can only search in the 1st page
and nothing else.
This is my formula for the pagination:
const [pageNumber, setPageNumber] = useState(0)
const bulletinsPerPage = 8
const pagesVisited = pageNumber * bulletinsPerPage
const pageCount = Math.ceil(bulletins.length / bulletinsPerPage)
This is the main code for the search function, slicing the pages and mapping the JSON list:
const displayBulletins = bulletins
.filter((bulletin) => {
if (searchTerm === '') {
return bulletin
} else if (bulletin.title.toLowerCase().includes(searchTerm.toLowerCase())) {
return bulletin
}
return false
})
.slice(pagesVisited, pagesVisited + bulletinsPerPage)
.map((bulletin) => {
return (
<>
<BulletinList
key={bulletin.bbID}
bulletin={bulletin}
onDelete={onDelete}
/>
</>
);
})
What I'm trying to understand is, how do I modify the current method so that the search function will work on any pages other than the 1st page
? The pagination thing is kind of new to me so I'm not sure which part should I start with.
Here's my codesandbox for reference:
Upvotes: 1
Views: 3425
Reputation: 4484
You need to set the page number to 1 when the search term changes because you're showing only the filtered entries. But you're calculating the total pages based on the total number of entries, instead of the filtered set of entries.
Have a look at this sandbox: https://codesandbox.io/s/kind-carson-1p926
I haven't used react-paginate
so I haven't set the active page to 1. You'll have to figure that out.
Upvotes: 2