Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

test.ts

451 lines13.4 KB

1import {
2 useMutation,
3 useQuery,
4 usePaginatedQuery,
5 useInfiniteQuery,
6 useIsFetching,
7 setConsole,
8 ReactQueryProviderConfig,
9} from 'react-query'
10​
11function simpleQuery() {
12 // Query - simple case
13 const querySimple = useQuery('todos', () => Promise.resolve('test'))
14 querySimple.data // $ExpectType string | undefined
15 querySimple.error // $ExpectType Error | null
16 querySimple.isFetching // $ExpectType boolean
17 querySimple.refetch() // $ExpectType Promise<string>
18 querySimple.fetchMore // $ExpectError
19 querySimple.canFetchMore // $ExpectError
20 querySimple.isFetchingMore // $ExpectError
22​
23function queryWithVariables() {
24 // Query Variables
25 const param = 'test'
26 const queryVariables = useQuery(
27 ['todos', { param }, 10],
28 (key, variables, id) => Promise.resolve(variables.param === 'test')
29 )
30​
31 queryVariables.data // $ExpectType boolean | undefined
32 queryVariables.refetch() // $ExpectType Promise<boolean>
33 queryVariables.refetch({ force: true }) // $ExpectType Promise<boolean>
35​
36function queryKeyArrayOrder() {
37 // first element in the key must be not null/undefined
38 useQuery([null, 'a'], async (id, key) => id) // $ExpectError
39​
40 useQuery([10, 'a'], async (id, key) => id)
41 useQuery([false, 'a'], async (id, key) => id)
42 useQuery([{ complex: { obj: "yes" } }, 'a'], async (id, key) => id)
44​
45function conditionalQuery(condition: boolean) {
46 const queryFn1 = (name: string, params: { bar: string }) =>
47 Promise.resolve(10)
48 const queryFn2 = () => Promise.resolve('test')
49​
50 // Query with falsey query key
51 useQuery(condition && ['foo', { bar: 'baz' }], queryFn1)
52 useQuery(condition && ['foo', { bar: 'baz' }], queryFn2)
53 useQuery({
54 queryKey: condition && ['foo', { bar: 'baz' }],
55 queryFn: queryFn1,
56 })
57​
58 // Query with query key function
59 useQuery(() => ['foo', { bar: 'baz' }], queryFn1)
60 useQuery(() => ['foo', { bar: 'baz' }], queryFn2)
62​
63function queryWithObjectSyntax(condition: boolean) {
64 useQuery({
65 queryKey: ['key'],
66 queryFn: async key => key,
67 }).data // $ExpectType string | undefined
68​
69 useQuery({
70 queryKey: ['key', 10],
71 variables: [true, 20],
72 queryFn: async (
73 key, // $ExpectType string
74 id, // $ExpectType number
75 var1, // $ExpectType boolean
76 var2 // $ExpectType number
77 ) => 'yay!',
78 }).data // $ExpectType string | undefined
79​
80 useQuery({
81 queryKey: 'key',
82 variables: [true, 20],
83 queryFn: async (
84 key, // $ExpectType "key"
85 var1, // $ExpectType boolean
86 var2 // $ExpectType number
87 ) => 'yay!',
88 }).data // $ExpectType string | undefined
89​
90 useQuery({
91 queryKey: condition && 'key',
92 queryFn: async (
93 key // $ExpectType "key"
94 ) => 10,
95 }).data // $ExpectType number | undefined
97​
98function queryWithNestedKey() {
99 // Query with nested variabes
100 const queryNested = useQuery(
101 [
102 'key',
103 {
104 nested: {
105 props: [1, 2],
106 },
107 },
108 ],
109 (key, variables) => Promise.resolve(variables.nested.props[0])
110 )
111 queryNested.data // $ExpectType number | undefined
113​
114function queryWithComplexKeysAndVariables() {
115 useQuery(['key', { a: 1 }], [{ b: { x: 1 } }, { c: { x: 1 } }], (
116 key1, // $ExpectType string
117 key2, // ExpectType { a: number }
118 var1, // $ExpectType { b: { x: number; }; }
119 var2 // $ExpectType { c: { x: number; }; }
120 ) =>
121 Promise.resolve(
122 key1 === 'key' && key2.a === 1 && var1.b.x === 1 && var2.c.x === 1
123 )
124 )
125​
126 // custom key
127 const longKey: [string, ...number[]] = ['key', 1, 2, 3, 4, 5]
128 useQuery(
129 longKey,
130 async (
131 key, // $ExpectType string
132 ...ids // $ExpectType number[]
133 ) => 100
134 ).data // $ExpectType number | undefined
135​
136 const longVariables: [boolean, ...object[]] = [true, {}]
137 useQuery(
138 ['key'],
139 longVariables,
140 async (
141 key, // $ExpectType string
142 var1, // $ExpectType boolean
143 ...vars // $ExpectType object[]
144 ) => 100
145 ).data // $ExpectType number | undefined
146​
147 // the following example cannot work properly, as it would require concatenating tuples with infinite tails.
148 // ts-toolbelt library's `List.Concat` cannot do the job. It would be possible to do with `typescript-tuple` and additional trick.
149 // useQuery<number, typeof longKey, typeof longVariables>(longKey, longVariables, async (
150 // key, // $ExpectType string // <-- currently boolean?!
151 // keyOrVar, // $ExpectType number | boolean // <-- currently object
152 // ...rest // $ExpectType number | object // <-- currently object[]
153 // ) => 100).data; // $ExpectType number | undefined
155​
156function paginatedQuery() {
157 // Paginated mode
158 const queryPaginated = usePaginatedQuery(
159 'key',
160 () => Promise.resolve({ data: [1, 2, 3], next: true }),
161 {
162 refetchInterval: 1000,
163 }
164 )
165 queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
166 queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
167 queryPaginated.data // $ExpectError
168​
169 // Discriminated union over status
170 if (queryPaginated.status === 'loading') {
171 queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
172 queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
173 queryPaginated.error // $ExpectType Error | null
174 }
175​
176 if (queryPaginated.status === 'error') {
177 queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; } | undefined
178 queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; } | undefined
179 queryPaginated.error // $ExpectType Error
180 }
181​
182 if (queryPaginated.status === 'success') {
183 queryPaginated.resolvedData // $ExpectType { data: number[]; next: boolean; }
184 queryPaginated.latestData // $ExpectType { data: number[]; next: boolean; }
185 queryPaginated.error // $ExpectType null
186 }
188​
189function paginatedQueryWithObjectSyntax(condition: boolean) {
190 usePaginatedQuery({
191 queryKey: condition && ['key', { a: 10 }],
192 variables: [true],
193 queryFn: async (key, { a }, debug) =>
194 key === 'key' && a === 10 && debug ? 'yes' : 'no',
195 }).latestData // $ExpectType "yes" | "no" | undefined
196 usePaginatedQuery({
197 queryKey: 'key',
198 variables: [true],
199 queryFn: async (key, debug) => (key === 'key' && debug ? 'yes' : 'no'),
200 }).latestData // $ExpectType "yes" | "no" | undefined
201 usePaginatedQuery({
202 queryKey: condition && (() => condition && 'key'),
203 variables: [10],
204 queryFn: async (key, level) =>
205 key === 'key' && level === 10 ? 'yes' : 'no',
206 }).latestData // $ExpectType "yes" | "no" | undefined
208​
209function simpleInfiniteQuery(condition: boolean) {
210 async function fetchWithCursor(key: string, cursor?: string) {
211 return [1, 2, 3]
212 }
213 function getFetchMore(last: number[], all: number[][]) {
214 return last.length ? String(all.length + 1) : false
215 }
216​
217 useInfiniteQuery<number[], [string], string>(['key'], fetchWithCursor, {
218 getFetchMore: (
219 last, // $ExpectType number[]
220 all // $ExpectType number[][]
221 ) => 'next',
222 // type of data in success is the array of results
223 onSuccess(
224 data // $ExpectType number[][]
225 ) {},
226 onSettled(
227 data, // $ExpectType number[][] | undefined
228 error // $ExpectType Error | null
229 ) {},
230 initialData: () =>
231 condition
232 ? [
233 [1, 2],
234 [2, 3],
235 ]
236 : undefined,
237 })
238 useInfiniteQuery(['key'], fetchWithCursor, { getFetchMore })
239 useInfiniteQuery('key', fetchWithCursor, { getFetchMore })
240 useInfiniteQuery(() => condition && 'key', fetchWithCursor, { getFetchMore })
241​
242 const infiniteQuery = useInfiniteQuery(['key'], fetchWithCursor, {
243 getFetchMore,
244 })
245​
246 // The next example does not work; the type for cursor does not get inferred.
247 // useInfiniteQuery(['key'], fetchWithCursor, {
248 // getFetchMore: (last, all) => 'string',
249 // });
250​
251 infiniteQuery.data // $ExpectType number[][]
252 infiniteQuery.fetchMore() // $ExpectType Promise<number[][]> | undefined
253 infiniteQuery.fetchMore('next') // $ExpectType Promise<number[][]> | undefined
255​
256function infiniteQueryWithObjectSyntax(condition: boolean) {
257 useInfiniteQuery({
258 queryKey: ['key', 1],
259 queryFn: async (key, id, next = 0) => ({ next: next + 1 }),
260 config: {
261 getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
262 },
263 }).data // $ExpectType { next: number; }[]
264 useInfiniteQuery({
265 queryKey: condition && (() => condition && ['key', 1]),
266 queryFn: async (key, id, next = 0) => ({ next: next + 1 }),
267 config: {
268 getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
269 },
270 }).data // $ExpectType { next: number; }[]
271 useInfiniteQuery({
272 queryKey: 'key',
273 queryFn: async (
274 key, // $ExpectType "key"
275 next = 0
276 ) => ({ next: next + 1 }),
277 config: {
278 getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
279 },
280 }).data // $ExpectType { next: number; }[]
281 useInfiniteQuery({
282 queryKey: condition && (() => condition && ('key' as const)),
283 queryFn: async (
284 key, // $ExpectType "key"
285 next = 0
286 ) => ({ next: next + 1 }),
287 config: {
288 getFetchMore: (last: { next: number }) => last.next, // annotation on this type is required to infer the type
289 },
290 }).data // $ExpectType { next: number; }[]
292​
293function log(...args: any[]) {}
294​
295function infiniteQueryWithVariables(condition: boolean) {
296 async function fetchWithCursor2(
297 key: string,
298 debuglog?: (...args: any[]) => void,
299 cursor?: string
300 ) {
301 if (debuglog) debuglog(key, cursor)
302 return [1, 2, 3]
303 }
304 function getFetchMore(last: number[], all: number[][]) {
305 return last.length ? String(all.length + 1) : false
306 }
307​
308 useInfiniteQuery<
309 number[],
310 [string],
311 [undefined | ((...args: any[]) => void)],
312 string
313 >(['key'], [undefined], fetchWithCursor2, {
314 getFetchMore: (last, all) => 'next',
315 })
316​
317 useInfiniteQuery(['key'], [log], fetchWithCursor2, { getFetchMore })
318 useInfiniteQuery('key', [log], fetchWithCursor2, { getFetchMore })
319 useInfiniteQuery(() => condition && 'key', [log], fetchWithCursor2, {
320 getFetchMore,
321 })
323​
324function simpleMutation() {
325 // Simple mutation
326 const mutation = () => Promise.resolve(['foo', 'bar'])
327​
328 const [mutate] = useMutation(mutation, {
329 onSuccess(result) {
330 result // $ExpectType string[]
331 },
332 })
333 mutate()
334 mutate(undefined, {
335 throwOnError: true,
336 onSettled(result, error) {
337 result // $ExpectType string[] | undefined
338 error // $ExpectType Error | null
339 },
340 })
341​
342 // Invalid mutatation funciton
343 useMutation((arg1: string, arg2: string) => Promise.resolve()) // $ExpectError
344 useMutation((arg1: string) => null) // $ExpectError
346​
347function mutationWithVariables() {
348 // Mutation with variables
349 const [mutateWithVars] = useMutation(
350 ({ param }: { param: number }) => Promise.resolve(Boolean(param)),
351 {
352 useErrorBoundary: true,
353 onMutate(variables) {
354 variables // $ExpectType { param: number; }
355 return { snapshot: variables.param }
356 },
357 }
358 )
359​
360 mutateWithVars(
361 { param: 1 },
362 {
363 async onSuccess(data) {
364 data // $ExpectType boolean
365 },
366 }
367 )
368​
369 mutateWithVars({ param: 'test' }) // $ExpectError
371​
372function helpers() {
373 useIsFetching() // $ExpectType number
374​
375 setConsole({ log, error: log, warn: log })
377​
378function globalConfig() {
379 const globalConfig: ReactQueryProviderConfig = {
380 onError(err, snapshot) {
381 log('Error', err, snapshot)
382 },
383 onMutate(variables) {
384 log(variables)
385 },
386 suspense: true,
387 isDataEqual: (oldData, newData) => oldData === newData,
388 }
390​
391function dataDiscriminatedUnion() {
392 // Query Variables
393 const param = 'test'
394 const queryResult = useQuery(['todos', { param }], (key, variables) =>
395 Promise.resolve([param])
396 )
397​
398 queryResult.data // $ExpectType string[] | undefined
399​
400 // Discriminated union over status
401 if (queryResult.status === 'loading') {
402 queryResult.data // $ExpectType string[] | undefined
403 queryResult.error // $ExpectType Error | null
404 }
405​
406 if (queryResult.status === 'error') {
407 // disabled
408 queryResult.data // $ExpectType string[] | undefined
409 queryResult.error // $ExpectType Error
410 }
411​
412 if (queryResult.status === 'success') {
413 // disabled
414 queryResult.data // $ExpectType string[]
415 queryResult.error // $ExpectType null
416 }
418​
419function mutationStatusDiscriminatedUnion() {
420 const mutation = () => Promise.resolve(['foo', 'bar'])
421 const [mutate, mutationState] = useMutation(mutation)
422 mutate()
423 // enabled
424 // TODO: handle invalid argument passed to mutationFn
425 // mutate('arg'); // $ExpectError
426 mutate('arg') // $ExpectError
427 mutationState.data // $ExpectType string[] | undefined
428​
429 // Discriminated union over status
430 if (mutationState.status === 'idle') {
431 mutationState.data // $ExpectType undefined
432 mutationState.error // $ExpectType null
433 }
434​
435 if (mutationState.status === 'loading') {
436 mutationState.data // $ExpectType undefined
437 // corrected
438 // mutationState.error; // $ExpectType null
439 mutationState.error // $ExpectType undefined
440 }
441​
442 if (mutationState.status === 'error') {
443 mutationState.data // $ExpectType undefined
444 mutationState.error // $ExpectType Error
445 }
446​
447 if (mutationState.status === 'success') {
448 mutationState.data // $ExpectType string[]
449 mutationState.error // $ExpectType undefined
450 }