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

Return null for useParams in pages #47490

Merged
merged 3 commits into from
Mar 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/next/navigation-types/compat/navigation.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,12 @@ declare module 'next/navigation' {
* router is not ready.
*/
export function usePathname(): string | null

/**
* Get the current parameters. For example useParams() on /dashboard/[team]
* where pathname is /dashboard/nextjs would return { team: 'nextjs' }
*
* If used from `pages/`, the hook will return `null`.
*/
export function useSearchParams(): ReadonlyURLSearchParams | null
}
16 changes: 9 additions & 7 deletions packages/next/src/client/components/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,6 @@ export function usePathname(): string {
return useContext(PathnameContext) as string
}

// TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead.
// export function useParams() {
// clientHookInServerComponentError('useParams')
// return useContext(ParamsContext)
// }

export {
ServerInsertedHTMLContext,
useServerInsertedHTML,
Expand Down Expand Up @@ -158,9 +152,17 @@ function getSelectedParams(
return getSelectedParams(node, params)
}

export function useParams() {
/**
* Get the current parameters. For example useParams() on /dashboard/[team]
* where pathname is /dashboard/nextjs would return { team: 'nextjs' }
*/
export function useParams(): Params {
clientHookInServerComponentError('useParams')
const { tree } = useContext(GlobalLayoutRouterContext)
if (!tree) {
// This only happens in `pages`. Type is overwritten in navigation.d.ts
return null!
}
return getSelectedParams(tree)
}

Expand Down