diff --git a/.changeset/firefox-addons-and-web-extensions-bug.md b/.changeset/firefox-addons-and-web-extensions-bug.md new file mode 100644 index 0000000000..668cc6cdac --- /dev/null +++ b/.changeset/firefox-addons-and-web-extensions-bug.md @@ -0,0 +1,5 @@ +--- +"react-router-dom": patch +--- + +Fixes an edge-case affecting web extensions in Firefox that use `URLSearchParams` and the `useSearchParams` hook. diff --git a/contributors.yml b/contributors.yml index 47a2659440..eda6c44c42 100644 --- a/contributors.yml +++ b/contributors.yml @@ -222,5 +222,6 @@ - yionr - yuleicul - zheng-chuang +- smithki - istarkov - louis-young diff --git a/packages/react-router-dom/__tests__/search-params-test.tsx b/packages/react-router-dom/__tests__/search-params-test.tsx index 298914fbec..6ad317670c 100644 --- a/packages/react-router-dom/__tests__/search-params-test.tsx +++ b/packages/react-router-dom/__tests__/search-params-test.tsx @@ -161,4 +161,25 @@ describe("useSearchParams", () => { expect(node.innerHTML).toMatch(/The current value is ""/); }); + + it("returns initial default values in search params", () => { + function SearchPage() { + let [searchParams] = useSearchParams({ a: "1", b: "2" }); + return

{searchParams.toString()}

; + } + + act(() => { + ReactDOM.createRoot(node).render( + + + } /> + + + ); + }); + + expect(node.innerHTML).toMatchInlineSnapshot( + `"

value=initial&a=1&b=2

"` + ); + }); }); diff --git a/packages/react-router-dom/dom.ts b/packages/react-router-dom/dom.ts index 9f1054ab41..c81b910387 100644 --- a/packages/react-router-dom/dom.ts +++ b/packages/react-router-dom/dom.ts @@ -97,13 +97,18 @@ export function getSearchParamsForLocation( let searchParams = createSearchParams(locationSearch); if (defaultSearchParams) { - for (let key of defaultSearchParams.keys()) { + // Use `defaultSearchParams.forEach(...)` here instead of iterating of + // `defaultSearchParams.keys()` to work-around a bug in Firefox related to + // web extensions. Relevant Bugzilla tickets: + // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602 + // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984 + defaultSearchParams.forEach((_, key) => { if (!searchParams.has(key)) { defaultSearchParams.getAll(key).forEach((value) => { searchParams.append(key, value); }); } - } + }); } return searchParams;