Unverified Commit 482e3fbf authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Change useSearchParams to URLSearchParams (#40978)

Similar to #40872 `useSearchParams` now returns a `URLSearchParams` instance instead of a plain object.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent ad1e8dd6
...@@ -147,12 +147,11 @@ function Router({ ...@@ -147,12 +147,11 @@ function Router({
typeof window === 'undefined' ? 'http://n' : window.location.href typeof window === 'undefined' ? 'http://n' : window.location.href
) )
// Convert searchParams to a plain object to match server-side. return {
const searchParamsObj: { [key: string]: string } = {} // This is turned into a readonly class in `useSearchParams`
url.searchParams.forEach((value, key) => { searchParams: url.searchParams,
searchParamsObj[key] = value pathname: url.pathname,
}) }
return { searchParams: searchParamsObj, pathname: url.pathname }
}, [canonicalUrl]) }, [canonicalUrl])
/** /**
......
import { createContext } from 'react' import { createContext } from 'react'
import type { NextParsedUrlQuery } from '../../server/request-meta'
export const SearchParamsContext = createContext<NextParsedUrlQuery>( export const SearchParamsContext = createContext<URLSearchParams>(null as any)
null as any
)
export const PathnameContext = createContext<string>(null as any) export const PathnameContext = createContext<string>(null as any)
export const ParamsContext = createContext(null as any) export const ParamsContext = createContext(null as any)
export const LayoutSegmentsContext = createContext(null as any) export const LayoutSegmentsContext = createContext(null as any)
......
// useLayoutSegments() // Only the segments for the current place. ['children', 'dashboard', 'children', 'integrations'] -> /dashboard/integrations (/dashboard/layout.js would get ['children', 'dashboard', 'children', 'integrations']) // useLayoutSegments() // Only the segments for the current place. ['children', 'dashboard', 'children', 'integrations'] -> /dashboard/integrations (/dashboard/layout.js would get ['children', 'dashboard', 'children', 'integrations'])
import { useContext } from 'react' import { useContext, useMemo } from 'react'
import { import {
SearchParamsContext, SearchParamsContext,
// ParamsContext, // ParamsContext,
...@@ -17,19 +17,66 @@ export { ...@@ -17,19 +17,66 @@ export {
useServerInsertedHTML, useServerInsertedHTML,
} from '../../shared/lib/server-inserted-html' } from '../../shared/lib/server-inserted-html'
/** const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol(
* Get the current search params. For example useSearchParams() would return {"foo": "bar"} when ?foo=bar 'internal for urlsearchparams readonly'
*/ )
export function useSearchParams() {
return useContext(SearchParamsContext) function readonlyURLSearchParamsError() {
return new Error('ReadonlyURLSearchParams cannot be modified')
}
class ReadonlyURLSearchParams {
[INTERNAL_URLSEARCHPARAMS_INSTANCE]: URLSearchParams
entries: URLSearchParams['entries']
forEach: URLSearchParams['forEach']
get: URLSearchParams['get']
getAll: URLSearchParams['getAll']
has: URLSearchParams['has']
keys: URLSearchParams['keys']
values: URLSearchParams['values']
toString: URLSearchParams['toString']
constructor(urlSearchParams: URLSearchParams) {
// Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.
this[INTERNAL_URLSEARCHPARAMS_INSTANCE] = urlSearchParams
this.entries = urlSearchParams.entries.bind(urlSearchParams)
this.forEach = urlSearchParams.forEach.bind(urlSearchParams)
this.get = urlSearchParams.get.bind(urlSearchParams)
this.getAll = urlSearchParams.getAll.bind(urlSearchParams)
this.has = urlSearchParams.has.bind(urlSearchParams)
this.keys = urlSearchParams.keys.bind(urlSearchParams)
this.values = urlSearchParams.values.bind(urlSearchParams)
this.toString = urlSearchParams.toString.bind(urlSearchParams)
}
[Symbol.iterator]() {
return this[INTERNAL_URLSEARCHPARAMS_INSTANCE][Symbol.iterator]()
}
append() {
throw readonlyURLSearchParamsError()
}
delete() {
throw readonlyURLSearchParamsError()
}
set() {
throw readonlyURLSearchParamsError()
}
sort() {
throw readonlyURLSearchParamsError()
}
} }
/** /**
* Get an individual search param. For example useSearchParam("foo") would return "bar" when ?foo=bar * Get the current search params. For example useSearchParams() would return {"foo": "bar"} when ?foo=bar
*/ */
export function useSearchParam(key: string): string | string[] { export function useSearchParams() {
const params = useContext(SearchParamsContext) const searchParams = useContext(SearchParamsContext)
return params[key] const readonlySearchParams = useMemo(() => {
return new ReadonlyURLSearchParams(searchParams)
}, [searchParams])
return readonlySearchParams
} }
// TODO-APP: Move the other router context over to this one // TODO-APP: Move the other router context over to this one
......
...@@ -9,10 +9,10 @@ export default function Page() { ...@@ -9,10 +9,10 @@ export default function Page() {
<> <>
<h1 <h1
id="params" id="params"
data-param-first={params.first ?? 'N/A'} data-param-first={params.get('first') ?? 'N/A'}
data-param-second={params.second ?? 'N/A'} data-param-second={params.get('second') ?? 'N/A'}
data-param-third={params.third ?? 'N/A'} data-param-third={params.get('third') ?? 'N/A'}
data-param-not-real={params.notReal ?? 'N/A'} data-param-not-real={params.get('notReal') ?? 'N/A'}
> >
hello from /hooks/use-search-params hello from /hooks/use-search-params
</h1> </h1>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment