Home > Back-end >  ReactJS my Search function not searching on every pages of pagination.What should I do?
ReactJS my Search function not searching on every pages of pagination.What should I do?

Time:01-25

My Search function only searching for products on 1 page of pagination.

    // Pagination source code ==============================================================
    const [currentPage, setCurrentPage] = useState(1)
    const [postsPerPage] = useState(6)

    const indexOfLastPost = currentPage * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = moviedata.slice(indexOfFirstPost, indexOfLastPost)
    const howManyPages = Math.ceil(moviedata.length/postsPerPage)

<div className='movieslist'>
     <div className='list'>
                                    {currentPosts.filter(u=>u.title.toLocaleLowerCase().includes(query)).map((fd, i) => {
    return <Card  img={fd.img} title={fd.title} quality={fd.quality} rating={fd.rating} price={fd.price} duration={fd.duration} year={fd.year} id={fd.id} allproduct={fd} allwishlist={fd} key={i} />
})}

    </div>

    <Pagination pages = {howManyPages} setCurrentPage={setCurrentPage}/>

</div>


I wanted to search the items of all pages, not just one page****but it only searches the items on one page

CodePudding user response:

1)

At first sight it seems like you are filtering currentPosts

If you want to search the items from all pages you should filter moviedata without slicing it before filter

2)

Of course it could require a bit reconstruct other parts if you need help let me know!

3) How to reconstruct

If your filter is constantly applied it should solve your problem

Notice that someString.includes('') // always returns true And if your query is empty you will get all of your data

    const [currentPage, setCurrentPage] = useState(1)
    const [postsPerPage] = useState(6)

    const filteredMovieData = moviedata.filter(()=>u=>u.title.toLocaleLowerCase().includes(query)) //new

    const indexOfLastPost = currentPage * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = filteredMovieData.slice(indexOfFirstPost, indexOfLastPost)
    const howManyPages = Math.ceil(filteredMovieData.length/postsPerPage)
  • Related