molefrog / wouter

šŸ„¢ A minimalist-friendly ~2.1KB routing for React and Preact

Home Page:https://npm.im/wouter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Intercept location change with custom hook swallows state

maciossek opened this issue Ā· comments

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

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);
    },
  ];
};

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