Skip to content

Commit

Permalink
Leverage useId for internal fetcher keys when available (#11166)
Browse files Browse the repository at this point in the history
  • Loading branch information
brophdawg11 committed Jan 9, 2024
1 parent d103537 commit e0d106b
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
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

0 comments on commit e0d106b

Please sign in to comment.