molefrog / wouter

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

Intercept location change with custom hook swallows state #425

Closed maciossek closed 7 months ago

maciossek commented 7 months ago

Hello there!

I am struggling to understand where the history state get's "swallowed" when having a custom hook. I forked the initial example and updated the dependencies. Currently logging the history.state or the useHistoryState() and sadly being null when using the custom hook. It works as intended when I remove the custom hook.

This is related to #39.

codesandbox

molefrog commented 7 months ago

state is one of the options of setLocation so you have to proxy the second argument (or better, rest of args):

const useLocationWithConfirmation = (...args) => {
  const historyState = useHistoryState();

  const [location, setLocation] = useBrowserLocation(...args);

  const ctx = useContext(LockContext);

  console.log(history.state, historyState);

  return [
    location,
    (newLocation, ...options) => {
      let perfomNavigation = true;
      if (ctx.lock) {
        perfomNavigation = window.confirm(ctx.message || "Are you sure?");
      }

      if (perfomNavigation) setLocation(newLocation,  ...options);
    },
  ];
};
maciossek commented 7 months ago

Wonderful, I totally missed that. Many thanks for the super quick reply! Also a big thank you for writing the lib!