Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I go back neglecting seach params with react-router-dom?

Now I have this => navigate(-1); which is part of a button that navigates back, and here's the function fired when the user clicks the button:

const handleClick = async (e: MouseEvent<HTMLButtonElement>) => {    
  try {
      //  go back is confirmed
      navigate(-1);
    }
  } catch (err) {
    // go back is cancelled
  }
}

but the situation is that the user can navigate though many pages and the history will be like this:

"/main" => "chat?page=1" => "chat?page=2" => "chat?page=3"

and if the user in page 3 and clicked on the back button, he will go back to page 2. How can I avoid all this page parameter and go directly from "/chat?page=3" to "/main"?

I tried removing the params using setSearchParams but it ended up moving the user to a new page and the stack became like this:

"/main" => "/chat?page=1" => "/chat?page=2" => "/chat?page=3" => "/chat"

like image 538
Nou Avatar asked Dec 28 '25 14:12

Nou


1 Answers

Make all the navigations that update the page search parameter redirects (e.g. REPLACE) instead of forward (e.g. PUSH) actions. This will maintain the history stack in such a way that any back navigation (e.g. POP) goes back to the expected page.

See useSearchParams:

The setSearchParams function works like navigate, but only for the search portion of the URL. Also note that the second arg to setSearchParams is the same type as the second arg to navigate.

Example:

Location Action Type History Stack
"/main" navigate({
  pathname: "/chat",
  search: "?page=1",
});
PUSH ["/main", "/chat?page=1"]
"/chat?page=1" setSearchParams(
  searchParams => {
    searchParams.set("page", 2);
    return searchParams;
  },
  { replace: true },
);
REPLACE ["/main", "/chat?page=2"]
"/chat?page=2" setSearchParams(
  searchParams => {
    searchParams.set("page", 3);
    return searchParams;
  },
  { replace: true },
);
REPLACE ["/main", "/chat?page=3"]
"/chat?page=3" navigate(-1); POP ["/main"]
like image 200
Drew Reese Avatar answered Dec 30 '25 23:12

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!