Skip to content

Commit

Permalink
fix(useParams): fix issue with useParams reading from null object (#6940
Browse files Browse the repository at this point in the history
)

* fix(useParams): fix issue with useParams reading from null object

fixed by returning empty object if route not mounted

Closes #6938

* test(useParams): test for unmatched route calling useParams
  • Loading branch information
brandon-pereira authored and timdorr committed Sep 27, 2019
1 parent d8904fa commit a32f779
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
21 changes: 21 additions & 0 deletions packages/react-router/modules/__tests__/useParams-test.js
Expand Up @@ -98,4 +98,25 @@ describe("useParams", () => {
});
});
});

describe("when the route isn't matched", () => {
it("returns empty object", () => {
let params;

function HomePage() {
params = useParams();
return null;
}

renderStrict(
<MemoryRouter initialEntries={["/home"]}>
<Route path="/not-the-current-route" children={() => <HomePage />} />
</MemoryRouter>,
node
);

expect(typeof params).toBe("object");
expect(Object.keys(params)).toHaveLength(0);
});
});
});
3 changes: 2 additions & 1 deletion packages/react-router/modules/hooks.js
Expand Up @@ -36,7 +36,8 @@ export function useParams() {
);
}

return useContext(Context).match.params;
const match = useContext(Context).match;
return match ? match.params : {};
}

export function useRouteMatch(path) {
Expand Down

0 comments on commit a32f779

Please sign in to comment.