Skip to content

Using useBlocker to save data before navigating away #12747

Closed Answered by eden-lane
eden-lane asked this question in Q&A
Discussion options

You must be logged in to vote

I'm not a fan of my solution, but it works for me:

const useBeforeNavigate = (callback: () => void) => {
  const location = useLocation();

  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      currentLocation.pathname !== nextLocation.pathname &&
      currentLocation.pathname === location.pathname,
  );

  useEffect(() => {
    if (blocker.state === 'blocked') {
      callback?.();
      blocker.proceed?.();
    }
  }, [blocker]);
};

We need to check if we're on the same location the hook was supposed to block, otherwise it blocks all other navigations.
As I said, it looks like a workaround, but I haven't found any other way to solve this.

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
1 reply
@eden-lane
Comment options

Comment options

You must be logged in to vote
2 replies
@eden-lane
Comment options

Answer selected by eden-lane
@rjgotten
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants