Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react pagination how to return to page 0 when chagne the category

when i change the category the pagination stell in the same page number and the other category page turn to blank page i want when change the category the page go to 0.

this is the spring boot api for display all the posts by category

    @GetMapping("/public/posts/category")
    public ResponseEntity<PageResponse<PostResponse>> getAllPostsByCategory(
            @RequestParam(name = "category", required = false) String categoryName,
            @RequestParam(name = "page", defaultValue = "0", required = false) int page,
            @RequestParam(name = "size", defaultValue = "10", required = false) int size
    ) {
        return new ResponseEntity<>(service.getAllPostsByCategory(page, size, categoryName), HttpStatus.OK);
    }

and this is the react route for the category page

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Route path="/category/:category" element={<CategoryPage />} />

How can I track the parameter change? and when it chagne set the page to 0

  const { category } = useParams();

  useEffect(() => {
    getPostsByCategory(category, pages, size).then((data) => {
      setContent(data.content);
      setTotalPages(data.totalPages);
    });
  }, [category, pages, size]);

  console.log(totalPages);

  return (
    <div className="h-[80vh] flex flex-col space-y-4 items-center justify-between">
      <div>
        {content.map((post) => (
          <Post key={post.id} post={post} />
        ))}
      </div>
      <Pageination pages={pages} setPages={setPages} totalPages={totalPages} />
    </div>
  );

>Solution :

You can add another useEffect with the dependency array of [category] and set the page value to 0 in there. This basically sets the page to 0 every time the category changes.

useEffect(() => {
  //pseudocode to represent changing the page value
  setPage(0)
}, [category])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading