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

Leverage useId for internal fetcher keys when available #11166

Merged
merged 1 commit into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fetcher-key-useid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Leverage `useId` for internal fetcher keys when available
Original file line number Diff line number Diff line change
Expand Up @@ -5368,9 +5368,11 @@ function testDomRouter(
{ window: getWindow("/") }
);
let { container } = render(<RouterProvider router={router} />);
expect(container.innerHTML).not.toMatch(/__\d+__,my-key/);
expect(container.innerHTML).not.toMatch(/my-key/);
await waitFor(() =>
expect(container.innerHTML).toMatch(/__\d+__,my-key/)
// React `useId()` results in either `:r2a:` or `:rp:` depending on
// `DataBrowserRouter`/`DataHashRouter`
expect(container.innerHTML).toMatch(/(:r2a:|:rp:),my-key/)
);
});
});
Expand Down
8 changes: 7 additions & 1 deletion packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,8 @@ const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
const FLUSH_SYNC = "flushSync";
const flushSyncImpl = ReactDOM[FLUSH_SYNC];
const USE_ID = "useId";
const useIdImpl = React[USE_ID];

function startTransitionSafe(cb: () => void) {
if (startTransitionImpl) {
Expand Down Expand Up @@ -1634,10 +1636,14 @@ export function useFetcher<TData = any>({
);

// Fetcher key handling
let [fetcherKey, setFetcherKey] = React.useState<string>(key || "");
// OK to call conditionally to feature detect `useId`
// eslint-disable-next-line react-hooks/rules-of-hooks
let defaultKey = useIdImpl ? useIdImpl() : "";
let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);
if (key && key !== fetcherKey) {
setFetcherKey(key);
} else if (!fetcherKey) {
// We will only fall through here when `useId` is not available
setFetcherKey(getUniqueFetcherId());
}

Expand Down