Skip to content

Fix: useBlocker stale blockerKey #13330

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

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@
- jungwoo3490
- justjavac
- kachun333
- KagaKyouichirou
- Kakamotobi
- kantuni
- kapil-patel
Expand Down
147 changes: 147 additions & 0 deletions packages/react-router/__tests__/useBlocker-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import * as React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { Blocker } from "react-router";
import {
Link,
Outlet,
RouterProvider,
createHashRouter,
useBlocker,
useLocation,
} from "react-router";

const Confirm: React.FC<{ blocker: Blocker }> = ({ blocker }) => {
const blocked = blocker.state === "blocked";
return blocked ? (
<div>
<button onClick={() => blocker.reset()}>CANCEL</button>
<button data-testid="bttnConfirm" onClick={() => blocker.proceed()}>
CONFIRM
</button>
</div>
) : null;
};

describe("useBlocker", () => {
it("is defensive against an unstable router object", async () => {
const A: React.FC<{ foo: boolean }> = ({ foo }) => {
return (
<>
<h2>A</h2>
<Link to={"/"}>TO HOME</Link>
<span data-testid="spanPageADisplayFoo">{`foo: ${foo}`}</span>
</>
);
};

const B: React.FC<{
setFoo: React.Dispatch<React.SetStateAction<boolean>>;
}> = ({ setFoo }) => {
let blocker = useBlocker(true);
return (
<>
<h2>B</h2>
<Link data-testid="linkBToHome" to={"/"}>
TO HOME
</Link>
<span
data-testid="spanReconstructRouter"
style={{
color: "blue",
textDecoration: "underline",
cursor: "pointer",
}}
onClick={() => setFoo((foo) => !foo)}
>
{"click to re-construct router"}
</span>
<Confirm blocker={blocker} />
</>
);
};

const Root: React.FC = () => {
const location = useLocation();
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<h1>ROOT</h1>
<div data-testid="location">{location.pathname}</div>
<Outlet />
</div>
);
};

const TestUnstableRouterObject: React.FC = () => {
const [foo, setFoo] = React.useState<boolean>(false);
const router = React.useMemo(() => {
console.log("reconstructing router... foo is: ", foo);
return createHashRouter([
{
path: "/",
Component: Root,
children: [
{
index: true,
element: (
<>
<h1>HOME</h1>
<Link data-testid="linkToPageA" to={"/a"}>
TO PAGE A
</Link>
<Link data-testid="linkToPageB" to={"/b"}>
TO PAGE B
</Link>
</>
),
},
{
path: "a",
element: <A foo={foo} />,
},
{
path: "b",
element: <B setFoo={setFoo} />,
},
],
},
]);
}, [foo]);

return <RouterProvider router={router} />;
};

render(<TestUnstableRouterObject />);

let expectLocation = (location: string) =>
expect(
screen.getByTestId<HTMLDivElement>("location").textContent
).toEqual(location);

expectLocation("/");

await userEvent.click(screen.getByTestId("linkToPageB"));
expectLocation("/b");

await userEvent.click(
screen.getByTestId<HTMLSpanElement>("spanReconstructRouter")
);
await userEvent.click(screen.getByTestId("linkBToHome"));

await userEvent.click(screen.getByTestId<HTMLButtonElement>("bttnConfirm"));
expectLocation("/");

await userEvent.click(screen.getByTestId("linkToPageA"));
expectLocation("/a");

expect(
screen.getByTestId<HTMLSpanElement>("spanPageADisplayFoo").textContent
).toEqual("foo: true");
});
});
12 changes: 7 additions & 5 deletions packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1257,7 +1257,6 @@ export function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {
let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);
let state = useDataRouterState(DataRouterStateHook.UseBlocker);

let [blockerKey, setBlockerKey] = React.useState("");
let blockerFunction = React.useCallback<BlockerFunction>(
(arg) => {
if (typeof shouldBlock !== "function") {
Expand Down Expand Up @@ -1290,11 +1289,13 @@ export function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {
[basename, shouldBlock]
);

let blockerKeyRef = React.useRef<string>("");

// This effect is in charge of blocker key assignment and deletion (which is
// tightly coupled to the key)
React.useEffect(() => {
let key = String(++blockerId);
setBlockerKey(key);
blockerKeyRef.current = key;
return () => router.deleteBlocker(key);
}, [router]);

Expand All @@ -1303,11 +1304,12 @@ export function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {
// effect so we don't get an orphaned blockerFunction in the router with a
// key of "". Until then we just have the IDLE_BLOCKER.
React.useEffect(() => {
if (blockerKey !== "") {
router.getBlocker(blockerKey, blockerFunction);
if (blockerKeyRef.current !== "") {
router.getBlocker(blockerKeyRef.current, blockerFunction);
}
}, [router, blockerKey, blockerFunction]);
}, [router, blockerFunction]);

let blockerKey = blockerKeyRef.current;
// Prefer the blocker from `state` not `router.state` since DataRouterContext
// is memoized so this ensures we update on blocker state updates
return blockerKey && state.blockers.has(blockerKey)
Expand Down