Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 18 additions & 8 deletions packages/nuqs/src/adapters/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ import { debugEnabled } from '../../lib/debug'
import { error } from '../../lib/errors'
import type { AdapterInterface, UseAdapterHook } from './defs'

export type AdapterContext = {
export type AdapterDefaultOptions = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: There are other things we could pass through that Context from adapter props, so this type could be more generically named AdapterProps, what do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah that makes a lot of sense. AdapterDefaultOptions is actually the defaultOptions object inside the AdapterProps 👍

5025028

defaultOptions?: {
shallow?: boolean
}
}

export type AdapterContext = AdapterDefaultOptions & {
useAdapter: UseAdapterHook
}

Expand All @@ -35,11 +41,11 @@ if (debugEnabled && typeof window !== 'undefined') {
window.__NuqsAdapterContext = context
}

export type AdapterProvider = ({
children
}: {
children: ReactNode
}) => ReactElement<ProviderProps<AdapterContext>>
export type AdapterProvider = (
props: AdapterDefaultOptions & {
children: ReactNode
}
) => ReactElement<ProviderProps<AdapterContext>>

/**
* Create a custom adapter (context provider) for nuqs to work with your framework / router.
Expand All @@ -52,10 +58,10 @@ export type AdapterProvider = ({
export function createAdapterProvider(
useAdapter: UseAdapterHook
): AdapterProvider {
return ({ children, ...props }: { children: ReactNode }) =>
return ({ children, defaultOptions, ...props }) =>
createElement(
context.Provider,
{ ...props, value: { useAdapter } },
{ ...props, value: { useAdapter, defaultOptions } },
children
)
}
Expand All @@ -67,3 +73,7 @@ export function useAdapter(): AdapterInterface {
}
return value.useAdapter()
}

export const useAdapterDefaultOptions =
(): AdapterDefaultOptions['defaultOptions'] =>
useContext(context).defaultOptions
7 changes: 4 additions & 3 deletions packages/nuqs/src/adapters/testing.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createElement, type ReactElement, type ReactNode } from 'react'
import { resetQueues } from '../lib/queues/reset'
import { renderQueryString } from '../lib/url-encoding'
import { context } from './lib/context'
import { type AdapterDefaultOptions, context } from './lib/context'
import type { AdapterInterface, AdapterOptions } from './lib/defs'

export type UrlUpdateEvent = {
Expand All @@ -18,10 +18,11 @@ type TestingAdapterProps = {
rateLimitFactor?: number
resetUrlUpdateQueueOnMount?: boolean
children: ReactNode
}
} & AdapterDefaultOptions

export function NuqsTestingAdapter({
resetUrlUpdateQueueOnMount = true,
defaultOptions,
...props
}: TestingAdapterProps): ReactElement {
if (resetUrlUpdateQueueOnMount) {
Expand All @@ -43,7 +44,7 @@ export function NuqsTestingAdapter({
})
return createElement(
context.Provider,
{ value: { useAdapter } },
{ value: { useAdapter, defaultOptions } },
props.children
)
}
Expand Down
21 changes: 21 additions & 0 deletions packages/nuqs/src/useQueryState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,24 @@ describe('useQueryState: update sequencing', () => {
expect(onUrlUpdate.mock.calls[0]![0].queryString).toEqual('?test=b')
})
})

describe('useQueryState: adapter defaults', () => {
it('should use adapter default value for `shallow` when provided', async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>()
const { result } = renderHook(() => useQueryState('test'), {
wrapper: withNuqsTestingAdapter({
searchParams: '?test=default',
defaultOptions: {
shallow: false
},
onUrlUpdate
})
})
expect(result.current[0]).toEqual('default')

await act(() => result.current[1]('update'))

expect(onUrlUpdate).toHaveBeenCalledOnce()
expect(onUrlUpdate.mock.calls[0]![0].options.shallow).toBe(false)
})
})
26 changes: 9 additions & 17 deletions packages/nuqs/src/useQueryState.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useId, useRef, useState } from 'react'
import { useAdapter } from './adapters/lib/context'
import { useAdapter, useAdapterDefaultOptions } from './adapters/lib/context'
import type { Options } from './defs'
import { debug } from './lib/debug'
import { debounceController } from './lib/queues/debounce'
Expand Down Expand Up @@ -202,9 +202,14 @@ export function useQueryState(
*/
export function useQueryState<T = string>(
key: string,
{
options: Partial<UseQueryStateOptions<T>> & {
defaultValue?: T
} = {}
) {
const defaultOptions = useAdapterDefaultOptions()
const {
history = 'replace',
shallow = true,
shallow = defaultOptions?.shallow ?? true,
scroll = false,
throttleMs = defaultRateLimit.timeMs,
limitUrlUpdates,
Expand All @@ -214,20 +219,7 @@ export function useQueryState<T = string>(
defaultValue = undefined,
clearOnDefault = true,
startTransition
}: Partial<UseQueryStateOptions<T>> & {
defaultValue?: T
} = {
history: 'replace',
scroll: false,
shallow: true,
throttleMs: defaultRateLimit.timeMs,
parse: x => x as unknown as T,
serialize: String,
eq: (a, b) => a === b,
clearOnDefault: true,
defaultValue: undefined
}
) {
} = options
const hookId = useId()
const adapter = useAdapter()
const { [key]: queuedQuery } = debounceController.useQueuedQueries([key])
Expand Down
23 changes: 23 additions & 0 deletions packages/nuqs/src/useQueryStates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,3 +683,26 @@ describe('useQueryStates: update sequencing', () => {
expect(onUrlUpdate.mock.calls[1]![0].queryString).toEqual('?a=debounced')
})
})

describe('useQueryStates: adapter defaults', () => {
it('should use adapter default value for `shallow` when provided', async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>()
const useTestHook = () => useQueryStates({ test: parseAsString })
const { result } = renderHook(useTestHook, {
wrapper: withNuqsTestingAdapter({
searchParams: '?test=default',
defaultOptions: {
shallow: false
},
onUrlUpdate
})
})

expect(result.current[0]).toEqual({ test: 'default' })

await act(() => result.current[1]({ test: 'update' }))

expect(onUrlUpdate).toHaveBeenCalledOnce()
expect(onUrlUpdate.mock.calls[0]![0].options.shallow).toBe(false)
})
})
18 changes: 11 additions & 7 deletions packages/nuqs/src/useQueryStates.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useAdapter } from './adapters/lib/context'
import { useAdapter, useAdapterDefaultOptions } from './adapters/lib/context'
import type { Nullable, Options, UrlKeys } from './defs'
import { debug } from './lib/debug'
import { debounceController } from './lib/queues/debounce'
Expand Down Expand Up @@ -64,18 +64,22 @@ const defaultUrlKeys = {}
*/
export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
keyMap: KeyMap,
{
options: Partial<UseQueryStatesOptions<KeyMap>> = {}
): UseQueryStatesReturn<KeyMap> {
const hookId = useId()
const defaultOptions = useAdapterDefaultOptions()

const {
history = 'replace',
scroll = false,
shallow = true,
shallow = defaultOptions?.shallow ?? true,
throttleMs = defaultRateLimit.timeMs,
limitUrlUpdates,
clearOnDefault = true,
startTransition,
urlKeys = defaultUrlKeys
}: Partial<UseQueryStatesOptions<KeyMap>> = {}
): UseQueryStatesReturn<KeyMap> {
const hookId = useId()
urlKeys = defaultUrlKeys as UrlKeys<KeyMap>
} = options

type V = NullableValues<KeyMap>
const stateKeys = Object.keys(keyMap).join(',')
const resolvedUrlKeys = useMemo(
Expand Down
Loading