Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for null before reading value in useParams #47875

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/next/src/client/components/navigation.ts
Expand Up @@ -159,12 +159,12 @@ function getSelectedParams(
*/
export function useParams(): Params {
clientHookInServerComponentError('useParams')
const { tree } = useContext(GlobalLayoutRouterContext)
if (!tree) {
const globalLayoutRouterContext = useContext(GlobalLayoutRouterContext)
if (!globalLayoutRouterContext) {
// This only happens in `pages`. Type is overwritten in navigation.d.ts
return null!
}
return getSelectedParams(tree)
return getSelectedParams(globalLayoutRouterContext.tree)
}

// TODO-APP: handle parallel routes
Expand Down
9 changes: 6 additions & 3 deletions test/e2e/app-dir/use-params/app/[id]/[id2]/page.tsx
@@ -1,11 +1,14 @@
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const { id, id2 } = useParams()
const params = useParams()
if (params === null) {
return null
}
return (
<div>
<div id="param-id">{id}</div>
<div id="param-id2">{id2}</div>
<div id="param-id">{params.id}</div>
<div id="param-id2">{params.id2}</div>
</div>
)
}
7 changes: 5 additions & 2 deletions test/e2e/app-dir/use-params/app/[id]/page.tsx
@@ -1,10 +1,13 @@
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const { id } = useParams()
const params = useParams()
if (params === null) {
return null
}
return (
<div>
<div id="param-id">{id}</div>
<div id="param-id">{params.id}</div>
</div>
)
}
10 changes: 10 additions & 0 deletions test/e2e/app-dir/use-params/pages/use-params-pages.js
@@ -0,0 +1,10 @@
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const params = useParams()
return (
<div>
<div id="params">{JSON.stringify(params)}</div>
</div>
)
}
6 changes: 6 additions & 0 deletions test/e2e/app-dir/use-params/use-params.test.ts
Expand Up @@ -36,5 +36,11 @@ createNextDescribe(
expect(await browser.elementByCss('#param-id').text()).toBe('a')
expect(await browser.elementByCss('#param-id2').text()).toBe('b')
})

it('should return null in pages', async () => {
const browser = await next.browser('/use-params-pages')

expect(await browser.elementByCss('#params').text()).toBe('null')
})
}
)