Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zhangyunhai2021 opened this issue May 27, 2024 · 1 comment
Labels

Comments

@zhangyunhai2021
Copy link

zhangyunhai2021 commented May 27, 2024

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
Copy link
Author

Has anyone else encountered the same problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant