-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathclient.ts
60 lines (55 loc) · 1.42 KB
/
client.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
import {
DehydratedState,
QueryClient,
QueryKey,
dehydrate,
hydrate,
} from '@tanstack/react-query'
/**
* Make a new instance of the react query client.
*/
export const makeReactQueryClient = (
/**
* Optionally hydrate the query client with dehydrated state.
*/
dehydratedState?: DehydratedState
) => {
const client = new QueryClient({
defaultOptions: {
queries: {
// Global default to 60 seconds.
staleTime: 60 * 1000,
},
},
})
// Hydate if dehydrated state is provided.
if (dehydratedState) {
hydrate(client, dehydratedState)
}
return client
}
/**
* Dehydrate query client and remove undefined values so it can be serialized.
*/
export const dehydrateSerializable: typeof dehydrate = (...args) => {
const dehydrated = dehydrate(...args)
return {
mutations: dehydrated.mutations,
queries: dehydrated.queries.map(({ queryKey, ...query }) => ({
...query,
queryKey: removeUndefinedFromQueryKey(queryKey) as QueryKey,
})),
}
}
const removeUndefinedFromQueryKey = (value: unknown): unknown =>
typeof value === 'object' && value !== null
? Object.fromEntries(
Object.entries(value).flatMap(([k, v]) =>
v === undefined ? [] : [[k, removeUndefinedFromQueryKey(v)]]
)
)
: Array.isArray(value)
? value.flatMap((v) =>
v === undefined ? [] : [removeUndefinedFromQueryKey(v)]
)
: value