Search function only work on the first page and not other pages (using react-paginate and .filter)

2.7k Views Asked by At

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

1

There are 1 best solutions below

3
On BEST ANSWER

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.