3

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.

Abraham Arreola
  • 329
  • 4
  • 14
  • The `history.replace` ***should*** be a REPLACE action. Think you could create a *running* codesandbox demo that reproduces this issue that we could inspect and debug live? – Drew Reese Feb 14 '22 at 18:28
  • Probably worth mentioning which version of RR you are using as well. – knownasilya Feb 14 '22 at 19:02
  • have you considered giving the dialog the ability to open without requiring a route change? aka decoupling it from the route change? – Kevin B Feb 14 '22 at 19:12
  • @knownasilya `useHistory` is a RRDv5 hook and `Prompt` is a RRDv4/5 component, OP is very likely on v5 with good certainty. – Drew Reese Feb 14 '22 at 19:49
  • @knownasilya I'm using v5.2.0, and it seems to be working fine when replacing for another pathname, but when replacing for the same pathname it's pushing it – Abraham Arreola Feb 14 '22 at 20:13
  • @KevinB Yeah, I actually have the implementation to open it without requiring the route change, but I doesn't convince me at all because the component I created has it's own state to control the dialog and this means that I need to declare another state where I'm using it and listen for the changes of this new state. Other than that, I want to know if this is an intentional behavior for this method or is a posible bug. – Abraham Arreola Feb 14 '22 at 20:19
  • Think you could create a *running* codesandbox demo that reproduces the issue we could inspect and debug live? – Drew Reese Feb 14 '22 at 21:25

1 Answers1

0

Seems to me that you want to reload, i.e. re-render, the page. For that, you can use history.go(0).

Take a look at this: How do I reload a page with react-router?

blend
  • 142
  • 5