Is it possible to dynamically set createSearchParamsCache default values? #736
-
I would like to be able to dynamically set the default values for some of the parameters outlined in the confirmBookingSearchParamsCache - is this possible?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Not out of the box, because the cache reference needs to be available for nested components to refer to, and dynamic values will likely be obtained during a page render (via However, you can update that reference at render time before parsing, with custom default values, and that would make it available for nested components. I tested this quickly in development mode using separate files and it seemed to work, YMMV. import {
createSearchParamsCache,
parseAsInteger,
parseAsString,
type SearchParams
} from 'nuqs/server'
type PageProps = {
searchParams: Promise<SearchParams>
}
type ConfirmBookingSearchParams = {
email: string
type: string
bayHours: number
guestPasses: number
sessionLength: number
peopleCount: number
}
function initializeCache(defaults: Partial<ConfirmBookingSearchParams> = {}) {
// Dummy defaults are needed to make the types non-nullable
return createSearchParamsCache({
email: parseAsString.withDefault(defaults.email ?? ''),
type: parseAsString.withDefault(defaults.type ?? ''),
bayHours: parseAsInteger.withDefault(defaults.bayHours ?? 0),
guestPasses: parseAsInteger.withDefault(defaults.guestPasses ?? 0),
sessionLength: parseAsInteger.withDefault(defaults.sessionLength ?? 0),
peopleCount: parseAsInteger.withDefault(defaults.peopleCount ?? 0)
})
}
let cache = initializeCache()
function updateCache(defaults: ConfirmBookingSearchParams) {
cache = initializeCache(defaults)
}
export default async function Page(props: PageProps) {
updateCache({
email: '[email protected]',
type: 'bar',
bayHours: 1,
guestPasses: 2,
sessionLength: 3,
peopleCount: 4
})
await cache.parse(props.searchParams)
return <NestedComponent />
}
export function NestedComponent() {
const search = cache.all()
return <pre>{JSON.stringify(search)}</pre>
} |
Beta Was this translation helpful? Give feedback.
Not out of the box, because the cache reference needs to be available for nested components to refer to, and dynamic values will likely be obtained during a page render (via
cookies
I assume).However, you can update that reference at render time before parsing, with custom default values, and that would make it available for nested components. I tested this quickly in development mode using separate files and it seemed to work, YMMV.