generated from chiffre-io/template-library
-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathuseQueryState.ts
304 lines (291 loc) · 9.57 KB
/
useQueryState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { useRouter, useSearchParams } from 'next/navigation.js' // https://github.com/47ng/nuqs/discussions/352
import React from 'react'
import { debug } from './debug'
import type { Options } from './defs'
import type { Parser } from './parsers'
import { emitter, type CrossHookSyncPayload } from './sync'
import {
FLUSH_RATE_LIMIT_MS,
enqueueQueryStringUpdate,
scheduleFlushToURL
} from './update-queue'
import { safeParse } from './utils'
export interface UseQueryStateOptions<T> extends Parser<T>, Options {}
export type UseQueryStateReturn<Parsed, Default> = [
Default extends undefined
? Parsed | null // value can't be null if default is specified
: Parsed,
<Shallow>(
value:
| null
| Parsed
| ((
old: Default extends Parsed ? Parsed : Parsed | null
) => Parsed | null),
options?: Options<Shallow>
) => Promise<URLSearchParams>
]
// Overload type signatures ----------------------------------------------------
// Note: the order of declaration matters (from the most specific to the least).
/**
* React state hook synchronized with a URL query string in Next.js
*
* This variant is used when providing a default value. This will make
* the returned state non-nullable when the query is not present in the URL.
* (the default value will be returned instead).
*
* _Note: the URL will **not** be updated with the default value if the query
* is missing._
*
* Setting the value to `null` will clear the query in the URL, and return
* the default value as state.
*
* Example usage:
* ```ts
* const [count, setCount] = useQueryState(
* 'count',
* parseAsInteger.defaultValue(0)
* )
*
* const increment = () => setCount(oldCount => oldCount + 1)
* const decrement = () => setCount(oldCount => oldCount - 1)
* // Clears the query key from the URL and `count` equals 0
* const clearCountQuery = () => setCount(null)
* ```
* @param key The URL query string key to bind to
* @param options - Parser (defines the state data type), default value and optional history mode.
*/
export function useQueryState<T>(
key: string,
options: UseQueryStateOptions<T> & { defaultValue: T }
): UseQueryStateReturn<
NonNullable<ReturnType<typeof options.parse>>,
typeof options.defaultValue
>
/**
* React state hook synchronized with a URL query string in Next.js
*
* If the query is missing in the URL, the state will be `null`.
*
* Example usage:
* ```ts
* // Blog posts filtering by tag
* const [tag, selectTag] = useQueryState('tag')
* const filteredPosts = posts.filter(post => tag ? post.tag === tag : true)
* const clearTag = () => selectTag(null)
* ```
* @param key The URL query string key to bind to
* @param options - Parser (defines the state data type), and optional history mode.
*/
export function useQueryState<T>(
key: string,
options: UseQueryStateOptions<T>
): UseQueryStateReturn<NonNullable<ReturnType<typeof options.parse>>, undefined>
/**
* Default type string, limited options & default value
*/
export function useQueryState(
key: string,
options: Options & {
defaultValue: string
}
): UseQueryStateReturn<string, typeof options.defaultValue>
/**
* React state hook synchronized with a URL query string in Next.js
*
* If the query is missing in the URL, the state will be `null`.
*
* Note: by default the state type is a `string`. To use different types,
* check out the `parseAsXYZ` helpers:
* ```ts
* const [date, setDate] = useQueryState(
* 'date',
* parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
* )
*
* const setToNow = () => setDate(new Date())
* const addOneHour = () => {
* setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
* }
* ```
* @param key The URL query string key to bind to
* @param options - Parser (defines the state data type), and optional history mode.
*/
export function useQueryState(
key: string,
options: Pick<UseQueryStateOptions<string>, keyof Options>
): UseQueryStateReturn<string, undefined>
/**
* React state hook synchronized with a URL query string in Next.js
*
* If the query is missing in the URL, the state will be `null`.
*
* Note: by default the state type is a `string`. To use different types,
* check out the `parseAsXYZ` helpers:
* ```ts
* const [date, setDate] = useQueryState(
* 'date',
* parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
* )
*
* const setToNow = () => setDate(new Date())
* const addOneHour = () => {
* setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
* }
* ```
* @param key The URL query string key to bind to
*/
export function useQueryState(
key: string
): UseQueryStateReturn<string, undefined>
/**
* React state hook synchronized with a URL query string in Next.js
*
* If used without a `defaultValue` supplied in the options, and the query is
* missing in the URL, the state will be `null`.
*
* ### Behaviour with default values:
*
* _Note: the URL will **not** be updated with the default value if the query
* is missing._
*
* Setting the value to `null` will clear the query in the URL, and return
* the default value as state.
*
* Example usage:
* ```ts
* // Blog posts filtering by tag
* const [tag, selectTag] = useQueryState('tag')
* const filteredPosts = posts.filter(post => tag ? post.tag === tag : true)
* const clearTag = () => selectTag(null)
*
* // With default values
*
* const [count, setCount] = useQueryState(
* 'count',
* parseAsInteger.defaultValue(0)
* )
*
* const increment = () => setCount(oldCount => oldCount + 1)
* const decrement = () => setCount(oldCount => oldCount - 1)
* const clearCountQuery = () => setCount(null)
*
* // --
*
* const [date, setDate] = useQueryState(
* 'date',
* parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
* )
*
* const setToNow = () => setDate(new Date())
* const addOneHour = () => {
* setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
* }
* ```
* @param key The URL query string key to bind to
* @param options - Parser (defines the state data type), optional default value and history mode.
*/
export function useQueryState<T = string>(
key: string,
{
history = 'replace',
shallow = true,
scroll = false,
throttleMs = FLUSH_RATE_LIMIT_MS,
parse = x => x as unknown as T,
serialize = String,
eq = (a, b) => a === b,
defaultValue = undefined,
clearOnDefault = false,
startTransition
}: Partial<UseQueryStateOptions<T>> & {
defaultValue?: T
} = {
history: 'replace',
scroll: false,
shallow: true,
throttleMs: FLUSH_RATE_LIMIT_MS,
parse: x => x as unknown as T,
serialize: String,
eq: (a, b) => a === b,
clearOnDefault: false,
defaultValue: undefined
}
) {
const router = useRouter()
// Not reactive, but available on the server and on page load
const initialSearchParams = useSearchParams()
const queryRef = React.useRef<string | null>(
initialSearchParams?.get(key) ?? null
)
const [internalState, setInternalState] = React.useState<T | null>(() => {
const query = initialSearchParams?.get(key) ?? null
return query === null ? null : safeParse(parse, query, key)
})
const stateRef = React.useRef(internalState)
debug(
'[nuqs `%s`] render - state: %O, iSP: %s',
key,
internalState,
initialSearchParams?.get(key) ?? null
)
React.useEffect(() => {
const query = initialSearchParams.get(key) ?? null
if (query === queryRef.current) {
return
}
const state = query === null ? null : safeParse(parse, query, key)
debug('[nuqs `%s`] syncFromUseSearchParams %O', key, state)
stateRef.current = state
queryRef.current = query
setInternalState(state)
}, [initialSearchParams?.get(key), key])
// Sync all hooks together & with external URL changes
React.useInsertionEffect(() => {
function updateInternalState({ state, query }: CrossHookSyncPayload) {
debug('[nuqs `%s`] updateInternalState %O', key, state)
stateRef.current = state
queryRef.current = query
setInternalState(state)
}
debug('[nuqs `%s`] subscribing to sync', key)
emitter.on(key, updateInternalState)
return () => {
debug('[nuqs `%s`] unsubscribing from sync', key)
emitter.off(key, updateInternalState)
}
}, [key])
const update = React.useCallback(
(stateUpdater: React.SetStateAction<T | null>, options: Options = {}) => {
let newValue: T | null = isUpdaterFunction(stateUpdater)
? stateUpdater(stateRef.current ?? defaultValue ?? null)
: stateUpdater
if (
(options.clearOnDefault ?? clearOnDefault) &&
newValue !== null &&
defaultValue !== undefined &&
eq(newValue, defaultValue)
) {
newValue = null
}
queryRef.current = enqueueQueryStringUpdate(key, newValue, serialize, {
// Call-level options take precedence over hook declaration options.
history: options.history ?? history,
shallow: options.shallow ?? shallow,
scroll: options.scroll ?? scroll,
throttleMs: options.throttleMs ?? throttleMs,
startTransition: options.startTransition ?? startTransition
})
// Sync all hooks state (including this one)
emitter.emit(key, { state: newValue, query: queryRef.current })
return scheduleFlushToURL(router)
},
[key, history, shallow, scroll, throttleMs, startTransition]
)
return [internalState ?? defaultValue ?? null, update]
}
function isUpdaterFunction<T>(
stateUpdater: React.SetStateAction<T>
): stateUpdater is (prevState: T) => T {
return typeof stateUpdater === 'function'
}