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"
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
setSearchParamsfunction works likenavigate, but only for the search portion of the URL. Also note that the second arg tosetSearchParamsis the same type as the second arg tonavigate.
Example:
| Location | Action | Type | History Stack |
|---|---|---|---|
"/main" |
navigate({ |
PUSH | ["/main", "/chat?page=1"] |
"/chat?page=1" |
setSearchParams( |
REPLACE | ["/main", "/chat?page=2"] |
"/chat?page=2" |
setSearchParams( |
REPLACE | ["/main", "/chat?page=3"] |
"/chat?page=3" |
navigate(-1); |
POP | ["/main"] |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With