Unverified Commit dc691433 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Ensure constructor for `useSearchParams` can be imported for `instanceof` checks (#87269)

parent ca831cfc
...@@ -2,6 +2,7 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types' ...@@ -2,6 +2,7 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { import {
createDevToolsInstrumentedPromise, createDevToolsInstrumentedPromise,
ReadonlyURLSearchParams,
type InstrumentedPromise, type InstrumentedPromise,
type NavigationPromises, type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
...@@ -9,7 +10,6 @@ import { ...@@ -9,7 +10,6 @@ import {
computeSelectedLayoutSegment, computeSelectedLayoutSegment,
getSelectedLayoutSegmentPath, getSelectedLayoutSegmentPath,
} from '../../shared/lib/segment' } from '../../shared/lib/segment'
import { ReadonlyURLSearchParams } from './readonly-url-search-params'
/** /**
* Promises are cached by tree to ensure stability across suspense retries. * Promises are cached by tree to ensure stability across suspense retries.
...@@ -28,7 +28,7 @@ const layoutSegmentPromisesCache = new WeakMap< ...@@ -28,7 +28,7 @@ const layoutSegmentPromisesCache = new WeakMap<
* Creates instrumented promises for layout segment hooks at a given tree level. * Creates instrumented promises for layout segment hooks at a given tree level.
* This is dev-only code for React Suspense DevTools instrumentation. * This is dev-only code for React Suspense DevTools instrumentation.
*/ */
export function createLayoutSegmentPromises( function createLayoutSegmentPromises(
tree: FlightRouterState tree: FlightRouterState
): LayoutSegmentPromisesCache | null { ): LayoutSegmentPromisesCache | null {
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
......
...@@ -11,12 +11,12 @@ import { ...@@ -11,12 +11,12 @@ import {
PathnameContext, PathnameContext,
PathParamsContext, PathParamsContext,
NavigationPromisesContext, NavigationPromisesContext,
ReadonlyURLSearchParams,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { import {
computeSelectedLayoutSegment, computeSelectedLayoutSegment,
getSelectedLayoutSegmentPath, getSelectedLayoutSegmentPath,
} from '../../shared/lib/segment' } from '../../shared/lib/segment'
import { ReadonlyURLSearchParams } from './readonly-url-search-params'
const useDynamicRouteParams = const useDynamicRouteParams =
typeof window === 'undefined' typeof window === 'undefined'
...@@ -61,15 +61,15 @@ export function useSearchParams(): ReadonlyURLSearchParams { ...@@ -61,15 +61,15 @@ export function useSearchParams(): ReadonlyURLSearchParams {
// In the case where this is `null`, the compat types added in // In the case where this is `null`, the compat types added in
// `next-env.d.ts` will add a new overload that changes the return type to // `next-env.d.ts` will add a new overload that changes the return type to
// include `null`. // include `null`.
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo((): ReadonlyURLSearchParams => {
if (!searchParams) { if (!searchParams) {
// When the router is not ready in pages, we won't have the search params // When the router is not ready in pages, we won't have the search params
// available. // available.
return null return null!
} }
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams)
}, [searchParams]) as ReadonlyURLSearchParams }, [searchParams])
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if (process.env.NODE_ENV !== 'production' && 'use' in React) { if (process.env.NODE_ENV !== 'production' && 'use' in React) {
...@@ -285,6 +285,11 @@ export function useSelectedLayoutSegment( ...@@ -285,6 +285,11 @@ export function useSelectedLayoutSegment(
export { unstable_isUnrecognizedActionError } from './unrecognized-action-error' export { unstable_isUnrecognizedActionError } from './unrecognized-action-error'
// Shared components APIs // Shared components APIs
export {
// We need the same class that was used to instantiate the context value
// Otherwise instanceof checks will fail in usercode
ReadonlyURLSearchParams,
}
export { export {
notFound, notFound,
forbidden, forbidden,
...@@ -292,6 +297,5 @@ export { ...@@ -292,6 +297,5 @@ export {
redirect, redirect,
permanentRedirect, permanentRedirect,
RedirectType, RedirectType,
ReadonlyURLSearchParams,
unstable_rethrow, unstable_rethrow,
} from './navigation.react-server' } from './navigation.react-server'
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { createContext } from 'react' import { createContext } from 'react'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { ReadonlyURLSearchParams } from '../../client/components/readonly-url-search-params'
export const SearchParamsContext = createContext<URLSearchParams | null>(null) export const SearchParamsContext = createContext<URLSearchParams | null>(null)
export const PathnameContext = createContext<string | null>(null) export const PathnameContext = createContext<string | null>(null)
...@@ -17,8 +18,8 @@ export type InstrumentedPromise<T> = Promise<T> & { ...@@ -17,8 +18,8 @@ export type InstrumentedPromise<T> = Promise<T> & {
export type NavigationPromises = { export type NavigationPromises = {
pathname: InstrumentedPromise<string> pathname: InstrumentedPromise<string>
searchParams: InstrumentedPromise<any> // ReadonlyURLSearchParams searchParams: InstrumentedPromise<ReadonlyURLSearchParams>
params: InstrumentedPromise<any> // Params params: InstrumentedPromise<Params>
// Layout segment hooks (updated at each layout boundary) // Layout segment hooks (updated at each layout boundary)
selectedLayoutSegmentPromises?: Map< selectedLayoutSegmentPromises?: Map<
string, string,
...@@ -44,6 +45,8 @@ export function createDevToolsInstrumentedPromise<T>( ...@@ -44,6 +45,8 @@ export function createDevToolsInstrumentedPromise<T>(
return promise return promise
} }
export { ReadonlyURLSearchParams }
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
SearchParamsContext.displayName = 'SearchParamsContext' SearchParamsContext.displayName = 'SearchParamsContext'
PathnameContext.displayName = 'PathnameContext' PathnameContext.displayName = 'PathnameContext'
......
'use client'
import { useSearchParams, ReadonlyURLSearchParams } from 'next/navigation'
import { useSyncExternalStore } from 'react'
export default function Page() {
const searchParams = useSearchParams()
const searchParamsClient = useSyncExternalStore(
() => {
return () => {}
},
() => {
return searchParams
},
() => {
return null
}
)
return (
<ul>
<li>
server:{' '}
<span data-testid="server" suppressHydrationWarning>
{searchParams instanceof ReadonlyURLSearchParams
? 'PASS instanceof check'
: `FAILED Received: "${String(searchParams)}" instead instanceof ${searchParams.constructor.name}`}
</span>
</li>
<li>
client:{' '}
<span data-testid="client">
{searchParamsClient === null
? '<pending>'
: searchParamsClient instanceof ReadonlyURLSearchParams
? 'PASS instanceof check'
: `FAILED Received: "${String(searchParamsClient)}" instead instanceof ${searchParamsClient.constructor.name}`}
</span>
</li>
</ul>
)
}
...@@ -71,6 +71,26 @@ describe('app dir - hooks', () => { ...@@ -71,6 +71,26 @@ describe('app dir - hooks', () => {
expect($('#params-not-real').text()).toBe('N/A') expect($('#params-not-real').text()).toBe('N/A')
}) })
} }
it('should be able to use instanceof ReadonlyURLSearchParams', async () => {
const browser = await next.browser(
'/hooks/use-search-params/instanceof?foo=bar'
)
const [server, client] = await Promise.all([
browser
.elementByCss('[data-testid="server"]')
.then((handle) => handle.text()),
browser
.elementByCss('[data-testid="client"]')
.then((handle) => handle.text()),
])
expect({ client, server }).toEqual({
server: 'PASS instanceof check',
client: 'PASS instanceof check',
})
})
}) })
describe('useDraftMode', () => { describe('useDraftMode', () => {
......
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