I have a React application where I’m implementing navigation between different pages. Here is the flow I need help with:
- The user starts on a main page, let’s call it Page A.
- From Page A, the user navigates to a subpage Page B (which will create page with unique id and treated as edit in te background).
- On Page B, on click of a button, it should:
– Before navigating the data created with unique id will be deleted.
– Navigate the user back to Page A.
– Remove the history entry of Page B completely so that if the user tries to go back or forward in the browser (to the already deleted page), they shouldn’t be able to, because they will see a error in this case.
I’ve tried using navigate(-1) to go back one step, but this still keeps Page B in the forward navigation stack. I also tried using navigate(‘..’, { replace: true }), but this seems to create duplicate entries in the history stack for Page A, which confuses users.
Expected solution:
I want to effectively "pop" the last history entry (Page B) so that once the user navigates back to Page A, they cannot use forward navigation to return to Page B.
The browser history should look like the user was never on Page B once they navigate back to Page A.
Is there a way to manipulate the browser history stack or use a different approach to achieve this behaviour?
Any insights or examples would be greatly appreciated!
2
Answers
history.replaceState(): This replaces the current history entry with new state data and URL. The user cannot navigate back to the replaced entry, effectively removing it from the user’s experience.
So, you have a situation where the user starts on Page A, then navigates to Page B where some data gets created. After some action on Page B, the user clicks a button to delete that data and return to Page A, but you want to make sure Page B is "removed" from the browser history.
Try this :