molefrog / wouter

🥢 A minimalist-friendly ~2.1KB routing for React and Preact
https://npm.im/wouter
The Unlicense
6.41k stars 146 forks source link

Prevent "back button" navigation #452

Open joecarl opened 1 month ago

joecarl commented 1 month ago

I'm developing an app where I need to prevent "back button" in some cases, (e.g.: when I'm editing a form and I click back button I should receive a confirmation dialog before the navigation occurs).

I tried adding the well known beforeunload event. But it only works when the navigation was not made via pushState/setLocation. Is it possible to achieve the behavior I need with wouter?

molefrog commented 1 month ago

You can try creating a custom hook that wraps default useBrowserLocation and checks for unsaved changes before actual navigate is called. Here, I found the demo that was initially written for V2 but I think it still works:

https://codesandbox.io/s/wouter-demo-interruptible-transition-v3-phrcz4?file=/src/index.js

joecarl commented 1 month ago

Thanks for your reply, but the provided link is not loading :( Anyway, are you sure that navigation caused by "browser's back button" can be prevented? I tried to create the custom hook as you suggested but I'm definetely missing some info.

molefrog commented 1 month ago

Hmm... I changed the sandbox visibility, could you try again?

joecarl commented 1 month ago

Thankyou.

Ok I tried the sandbox and it doesn't seem to address my issue. I followed these steps:

  1. Go to "About us".
  2. Dialog appears (nice), click confirm.
  3. Go to "Form" again.
  4. Then hit back button. At this point I would expect a confirmation dialog, but navigation occurs without confirmation. This is the issue I'm facing.