Skip to content

Commit

Permalink
Fix generatePath when passed a zero value param (#10612)
Browse files Browse the repository at this point in the history
  • Loading branch information
brophdawg11 committed Jun 15, 2023
1 parent 3d4868b commit 73cd01e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/purple-islands-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Fix `generatePath` when passed a numeric `0` value parameter
8 changes: 8 additions & 0 deletions packages/react-router/__tests__/generatePath-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ describe("generatePath", () => {
})
).toBe("/courses/foo*");
});
it("handles a 0 parameter", () => {
// @ts-expect-error
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
expect(generatePath("/courses/:id", { id: 0 })).toBe("/courses/0");
// @ts-expect-error
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
expect(generatePath("/courses/*", { "*": 0 })).toBe("/courses/0");
});
});

describe("with extraneous params", () => {
Expand Down
19 changes: 6 additions & 13 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,9 @@ export function generatePath<Path extends string>(
// ensure `/` is added at the beginning if the path is absolute
const prefix = path.startsWith("/") ? "/" : "";

const stringify = (p: any) =>
p == null ? "" : typeof p === "string" ? p : String(p);

const segments = path
.split(/\/+/)
.map((segment, index, array) => {
Expand All @@ -770,26 +773,16 @@ export function generatePath<Path extends string>(
// only apply the splat if it's the last segment
if (isLastSegment && segment === "*") {
const star = "*" as PathParam<Path>;
const starParam = params[star];

// Apply the splat
return starParam;
return stringify(params[star]);
}

const keyMatch = segment.match(/^:(\w+)(\??)$/);
if (keyMatch) {
const [, key, optional] = keyMatch;
let param = params[key as PathParam<Path>];

if (optional === "?") {
return param == null ? "" : param;
}

if (param == null) {
invariant(false, `Missing ":${key}" param`);
}

return param;
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
return stringify(param);
}

// Remove any optional markers from optional static segments
Expand Down

0 comments on commit 73cd01e

Please sign in to comment.