Skip to content

Commit 73cd01e

Browse files
authored
Fix generatePath when passed a zero value param (#10612)
1 parent 3d4868b commit 73cd01e

File tree

3 files changed

+19
-13
lines changed

3 files changed

+19
-13
lines changed

.changeset/purple-islands-cough.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router": patch
3+
---
4+
5+
Fix `generatePath` when passed a numeric `0` value parameter

packages/react-router/__tests__/generatePath-test.tsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ describe("generatePath", () => {
4444
})
4545
).toBe("/courses/foo*");
4646
});
47+
it("handles a 0 parameter", () => {
48+
// @ts-expect-error
49+
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
50+
expect(generatePath("/courses/:id", { id: 0 })).toBe("/courses/0");
51+
// @ts-expect-error
52+
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
53+
expect(generatePath("/courses/*", { "*": 0 })).toBe("/courses/0");
54+
});
4755
});
4856

4957
describe("with extraneous params", () => {

packages/router/utils.ts

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,9 @@ export function generatePath<Path extends string>(
762762
// ensure `/` is added at the beginning if the path is absolute
763763
const prefix = path.startsWith("/") ? "/" : "";
764764

765+
const stringify = (p: any) =>
766+
p == null ? "" : typeof p === "string" ? p : String(p);
767+
765768
const segments = path
766769
.split(/\/+/)
767770
.map((segment, index, array) => {
@@ -770,26 +773,16 @@ export function generatePath<Path extends string>(
770773
// only apply the splat if it's the last segment
771774
if (isLastSegment && segment === "*") {
772775
const star = "*" as PathParam<Path>;
773-
const starParam = params[star];
774-
775776
// Apply the splat
776-
return starParam;
777+
return stringify(params[star]);
777778
}
778779

779780
const keyMatch = segment.match(/^:(\w+)(\??)$/);
780781
if (keyMatch) {
781782
const [, key, optional] = keyMatch;
782783
let param = params[key as PathParam<Path>];
783-
784-
if (optional === "?") {
785-
return param == null ? "" : param;
786-
}
787-
788-
if (param == null) {
789-
invariant(false, `Missing ":${key}" param`);
790-
}
791-
792-
return param;
784+
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
785+
return stringify(param);
793786
}
794787

795788
// Remove any optional markers from optional static segments

0 commit comments

Comments
 (0)