1

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:

codesandbox

Lance
  • 215
  • 1
  • 6
  • 21

1 Answers1

2

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.

nullptr
  • 3,701
  • 2
  • 16
  • 40
  • I see, so the attempt that you've tried to set the active page to 1 is this line ``` { setSearchTerm(e.target.value); handlePageChange({ selected: 0 }); }} />``` right? And this is the part where I need to figure it out how to do it with ```react-paginate``` ? – Lance Oct 11 '21 at 09:03
  • @Lance yes. there should be a way to pass the current page to `react-paginate`, right? That's what I didn't implement. You have to set the current page to 1 anyway, because after filtering, there might not be enough results for more than one page. – nullptr Oct 11 '21 at 13:04
  • Yes, you're right. I've found the way to set the current page in ```react-paginate```, which is using the ```forcePage``` props by doing ```forcePage={pageNumber}```. Thanks for your help, really appreciate it! – Lance Oct 12 '21 at 02:02