-
-
Notifications
You must be signed in to change notification settings - Fork 894
/
Copy pathindex.tsx
190 lines (174 loc) · 5.76 KB
/
index.tsx
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
import { Fragment } from 'react'
import {
QueryClientProvider,
dehydrate,
hashKey,
hydrate,
} from '@tanstack/react-query'
import { isRedirect } from '@tanstack/router-core'
import type { AnyRouter } from '@tanstack/react-router'
import type {
QueryClient,
QueryObserverResult,
UseQueryOptions,
} from '@tanstack/react-query'
type AdditionalOptions = {
WrapProvider?: (props: { children: any }) => React.JSX.Element
/**
* If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.
*
* @default true
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)
*/
handleRedirects?: boolean
}
export type ValidateRouter<TRouter extends AnyRouter> =
NonNullable<TRouter['options']['context']> extends {
queryClient: QueryClient
}
? TRouter
: never
export function routerWithQueryClient<TRouter extends AnyRouter>(
router: ValidateRouter<TRouter>,
queryClient: QueryClient,
additionalOpts?: AdditionalOptions,
): TRouter {
const seenQueryKeys = new Set<string>()
const streamedQueryKeys = new Set<string>()
const ogClientOptions = queryClient.getDefaultOptions()
queryClient.setDefaultOptions({
...ogClientOptions,
queries: {
...ogClientOptions.queries,
_experimental_beforeQuery: (options: UseQueryOptions) => {
// Call the original beforeQuery
;(ogClientOptions.queries as any)?._experimental_beforeQuery?.(options)
const hash = options.queryKeyHashFn || hashKey
// On the server, check if we've already seen the query before
if (router.isServer) {
if (seenQueryKeys.has(hash(options.queryKey))) {
return
}
seenQueryKeys.add(hash(options.queryKey))
// If we haven't seen the query and we have data for it,
// That means it's going to get dehydrated with critical
// data, so we can skip the injection
if (queryClient.getQueryData(options.queryKey) !== undefined) {
;(options as any).__skipInjection = true
return
}
} else {
// On the client, pick up the deferred data from the stream
const dehydratedClient = router.clientSsr!.getStreamedValue<any>(
'__QueryClient__' + hash(options.queryKey),
)
// If we have data, hydrate it into the query client
if (dehydratedClient && !dehydratedClient.hydrated) {
dehydratedClient.hydrated = true
hydrate(queryClient, dehydratedClient)
}
}
},
_experimental_afterQuery: (
options: UseQueryOptions,
_result: QueryObserverResult,
) => {
// On the server (if we're not skipping injection)
// send down the dehydrated query
const hash = options.queryKeyHashFn || hashKey
if (
router.isServer &&
!(options as any).__skipInjection &&
queryClient.getQueryData(options.queryKey) !== undefined &&
!streamedQueryKeys.has(hash(options.queryKey))
) {
streamedQueryKeys.add(hash(options.queryKey))
router.serverSsr!.streamValue(
'__QueryClient__' + hash(options.queryKey),
dehydrate(queryClient, {
shouldDehydrateMutation: () => false,
shouldDehydrateQuery: (query) =>
hash(query.queryKey) === hash(options.queryKey),
}),
)
}
// Call the original afterQuery
;(ogClientOptions.queries as any)?._experimental_afterQuery?.(
options,
_result,
)
},
} as any,
})
if (additionalOpts?.handleRedirects ?? true) {
const ogMutationCacheConfig = queryClient.getMutationCache().config
queryClient.getMutationCache().config = {
...ogMutationCacheConfig,
onError: (error, _variables, _context, _mutation) => {
if (isRedirect(error)) {
return router.navigate(
router.resolveRedirect({
...error,
_fromLocation: router.state.location,
}),
)
}
return ogMutationCacheConfig.onError?.(
error,
_variables,
_context,
_mutation,
)
},
}
const ogQueryCacheConfig = queryClient.getQueryCache().config
queryClient.getQueryCache().config = {
...ogQueryCacheConfig,
onError: (error, _query) => {
if (isRedirect(error)) {
return router.navigate(
router.resolveRedirect({
...error,
_fromLocation: router.state.location,
}),
)
}
return ogQueryCacheConfig.onError?.(error, _query)
},
}
}
const ogOptions = router.options
router.options = {
...router.options,
dehydrate: () => {
return {
...ogOptions.dehydrate?.(),
// When critical data is dehydrated, we also dehydrate the query client
dehydratedQueryClient: dehydrate(queryClient),
}
},
hydrate: (dehydrated: any) => {
ogOptions.hydrate?.(dehydrated)
// On the client, hydrate the query client with the dehydrated data
hydrate(queryClient, dehydrated.dehydratedQueryClient)
},
context: {
...ogOptions.context,
// Pass the query client to the context, so we can access it in loaders
queryClient,
},
// Wrap the app in a QueryClientProvider
Wrap: ({ children }) => {
const OuterWrapper = additionalOpts?.WrapProvider || Fragment
const OGWrap = ogOptions.Wrap || Fragment
return (
<OuterWrapper>
<QueryClientProvider client={queryClient}>
<OGWrap>{children}</OGWrap>
</QueryClientProvider>
</OuterWrapper>
)
},
}
return router
}