react-router icon indicating copy to clipboard operation
react-router copied to clipboard

[Bug]: when click browser's back button the useBlocker hook could not block the navigate rightly

Open zhangyunhai2021 opened this issue 8 months ago • 1 comments

What version of React Router are you using?

6.23.1

Steps to Reproduce

I click browser's back button the location changes to a next location and then the confirm show, when I choose ok, the location changes back and not navigate ,why? Then I try to add navigate() method, the page navigate rightly but when I repeat last action the location change to the next location but the page nothing happened, so I click the back button secondly, the confirm show, why? the following code

export const useGuard = (hasSaved: boolean) => {
  // const navigate = useNavigate();
  const shouldBlock = useCallback<BlockerFunction>(
    ({ currentLocation, nextLocation }) => !hasSaved && currentLocation.pathname !== nextLocation.pathname,
    [hasSaved]
  );
  const blocker = useBlocker(shouldBlock);
  useEffect(() => {
    if (blocker.state === 'blocked' && hasSaved) {
      blocker.reset();
    }
    // for refresh
    if (!hasSaved) {
      window.onbeforeunload = (e) => {
        e.preventDefault();
        return '';
      };
    }
    // for route change
    if (blocker.state === 'blocked') {
      const isOK = window.confirm('Are you sure you want to leave?');
      if (isOK) {
        blocker.proceed();
        // navigate(blocker.location.pathname);
      } else {
        blocker.reset();
      }
    }
    return () => {
      window.onbeforeunload = null;
    };
  }, [hasSaved, blocker]);
};

Expected Behavior

I hope that when click the back button the location not change and the confirm show, while i choose ok,the location change to the next location and the page change

Actual Behavior

Actual performance is as above

zhangyunhai2021 avatar May 27 '24 07:05 zhangyunhai2021