I'm working on a react project where I created a component using <Promp/>
from react-router
to implement a confirm dialog that shows up when user attempts to leave the route without saving current changes:
The component works properly when I try to leave the current route, but I also want to display the dialog when user clicks a button meant to discard the changes intentionally. Since modal only displays based on a route change, a workaround that I could think of is to call history.push
when button clicked:
const history = useHistory();
const { pathname } = useLocation();
const onCancel = () => {
history.push(pathname);
};
that it pushes the same route and this way changes are discarded and user stays on the same page as if nothing happens, but now the problem with this workaround is that user won't be able to go back to previous route because history stack is getting filled with the same location, so in order to solve this I tried to use history.replace
which is meant to replace the top of the stack instead of pushing a new element, but it's not working this way and is acting like history.push
adding new elements with the same location.
Is this bug or am I missing something? what could be a workaround for this?
Any suggestion is welcome.