Skip to content

[Bug]: useBlocker fails when blocking function is quick to proceed #11613

@Artur-

Description

@Artur-

What version of React Router are you using?

6.23.1

Steps to Reproduce

Take the example from https://github.com/remix-run/react-router/blob/main/examples/navigation-blocking/src/app.tsx

and remove the user input based confirmation and replace it with an immediate confirmation, e.g. something like

 // Reset the blocker if the user cleans the form React.useEffect(() => { if (blocker.state === 'blocked' && value === '') { blocker.reset(); } else if (blocker.state === 'blocked') { blocker.proceed(); } }, [blocker, value]); 

Full code in https://stackblitz.com/edit/github-qwtgqt

Expected Behavior

When you go to view "One", then to the form view, enter "123" in the field and press back in the browser, you should end up on the "One" view as the blocker allows proceeding.

Actual Behavior

You remain on the form view (this might be dependent on the machine and the browser, tested with Chrome on a M1 mac). In another test case where the proceed function call takes a very short time, the back navigation succeeds around 80% of the time.

I think this is because the blocker functionality that in this case immediately after the user's back navigation will navigate forward and then back again. This does not work because history.go is asynchronous and you are supposed to wait for a popstate before calling it again: https://developer.mozilla.org/en-US/docs/Web/API/History/go

Similarly, if you do something like this in JS

for (let i=1; i <= 5; i++) { history.pushState( { myState: "url"+i+"state" },"","url" + i); } window.addEventListener("popstate", e => console.log("popstate with url",window.location.pathname,"and state",e.state)); history.go(-1); history.go(1); history.go(-1); 

You will only see two popstate events, and for paths 4 and 3.

If you use short delay instead, like

setTimeout(()=> history.go(-1),100); setTimeout(()=> history.go(1),200); setTimeout(()=> history.go(-1),300); 

you see the expected three events and actually end up on the correct history entry

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions