Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2import { queryKey } from '@tanstack/query-test-utils'
3import { queryOptions, useQuery } from '../index'
4import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
5β
6describe('useQuery', () => {
7 const key = queryKey()
8β
9 // unspecified query function should default to unknown
10 const noQueryFn = useQuery(() => ({ queryKey: key }))
11 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
12 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
13β
14 // it should infer the result type from the query function
15 const fromQueryFn = useQuery(() => ({
16 queryKey: key,
17 queryFn: () => 'test',
18 }))
19 expectTypeOf(fromQueryFn.data).toEqualTypeOf<string | undefined>()
20 expectTypeOf(fromQueryFn.error).toEqualTypeOf<Error | null>()
21β
22 // it should be possible to specify the result type
23 const withResult = useQuery<string>(() => ({
24 queryKey: key,
25 queryFn: () => 'test',
26 }))
27 expectTypeOf(withResult.data).toEqualTypeOf<string | undefined>()
28 expectTypeOf(withResult.error).toEqualTypeOf<Error | null>()
29β
30 // it should be possible to specify the error type
31 const withError = useQuery<string, Error>(() => ({
32 queryKey: key,
33 queryFn: () => 'test',
34 }))
35 expectTypeOf(withError.data).toEqualTypeOf<string | undefined>()
36 expectTypeOf(withError.error).toEqualTypeOf<Error | null>()
37β
38 // it should provide the result type in the configuration
39 useQuery(() => ({
40 queryKey: [key],
41 queryFn: () => true,
42 }))
43β
44 // it should be possible to specify a union type as result type
45 const unionTypeSync = useQuery(() => ({
46 queryKey: key,
47 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
48 }))
49 expectTypeOf(unionTypeSync.data).toEqualTypeOf<'a' | 'b' | undefined>()
50 const unionTypeAsync = useQuery<'a' | 'b'>(() => ({
51 queryKey: key,
52 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
53 }))
54 expectTypeOf(unionTypeAsync.data).toEqualTypeOf<'a' | 'b' | undefined>()
55β
56 // should error when the query function result does not match with the specified type
57 // @ts-expect-error
58 useQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' }))
59β
60 // it should infer the result type from a generic query function
61 function queryFn<T = string>(): Promise<T> {
62 return Promise.resolve({} as T)
63 }
64β
65 const fromGenericQueryFn = useQuery(() => ({
66 queryKey: key,
67 queryFn: () => queryFn(),
68 }))
69 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string | undefined>()
70 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
71β
72 const fromGenericOptionsQueryFn = useQuery(() => ({
73 queryKey: key,
74 queryFn: () => queryFn(),
75 }))
76 expectTypeOf(fromGenericOptionsQueryFn.data).toEqualTypeOf<
77 string | undefined
78 >()
79 expectTypeOf(fromGenericOptionsQueryFn.error).toEqualTypeOf<Error | null>()
80β
81 type MyData = number
82 type MyQueryKey = readonly ['my-data', number]
83β
84 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
85 queryKey: [, n],
86 }) => {
87 return n + 42
88 }
89β
90 useQuery(() => ({
91 queryKey: ['my-data', 100] as const,
92 queryFn: getMyDataArrayKey,
93 }))
94β
95 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
96 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
97 return Number(context.queryKey[0]) + 42
98 }
99β
100 useQuery(() => ({
101 queryKey: ['1'] as ['1'],
102 queryFn: getMyDataStringKey,
103 }))
104β
105 // it should handle query-functions that return Promise<any>
106 useQuery(() => ({
107 queryKey: key,
108 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
109 }))
110β
111 // handles wrapped queries with custom fetcher passed as inline queryFn
112 const useWrappedQuery = <
113 TQueryKey extends [string, Record<string, unknown>?],
114 TQueryFnData,
115 TError,
116 TData = TQueryFnData,
117 >(
118 qk: TQueryKey,
119 fetcher: (
120 obj: TQueryKey[1],
121 token: string,
122 // return type must be wrapped with TQueryFnReturn
123 ) => Promise<TQueryFnData>,
124 options?: OmitKeyof<
125 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
126 'queryKey' | 'queryFn' | 'initialData',
127 'safely'
128 >,
129 ) =>
130 useQuery(() => ({
131 queryKey: qk,
132 queryFn: () => fetcher(qk[1], 'token'),
133 ...options,
134 }))
135 const test = useWrappedQuery([''], () => Promise.resolve('1'))
136 expectTypeOf(test.data).toEqualTypeOf<string | undefined>()
137β
138 // handles wrapped queries with custom fetcher passed directly to useQuery
139 const useWrappedFuncStyleQuery = <
140 TQueryKey extends [string, Record<string, unknown>?],
141 TQueryFnData,
142 TError,
143 TData = TQueryFnData,
144 >(
145 qk: TQueryKey,
146 fetcher: () => Promise<TQueryFnData>,
147 options?: OmitKeyof<
148 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
149 'queryKey' | 'queryFn' | 'initialData',
150 'safely'
151 >,
152 ) => useQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
153 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
154 Promise.resolve(true),
155 )
156 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
157β
158 describe('initialData', () => {
159 describe('Config object overload', () => {
160 it('TData should always be defined when initialData is provided as an object', () => {
161 const { data } = useQuery(() => ({
162 queryKey: queryKey(),
163 queryFn: () => ({ wow: true }),
164 initialData: { wow: true },
165 }))
166β
167 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
168 })
169β
170 it('TData should be defined when passed through queryOptions', () => {
171 const options = queryOptions({
172 queryKey: queryKey(),
173 queryFn: () => ({ wow: true }),
174 initialData: { wow: true },
175 })
176 const { data } = useQuery(() => options)
177β
178 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
179 })
180β
181 it('TData should always be defined when initialData is provided as a function which ALWAYS returns the data', () => {
182 const { data } = useQuery(() => ({
183 queryKey: queryKey(),
184 queryFn: () => ({ wow: true }),
185 initialData: () => ({ wow: true }),
186 }))
187β
188 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
189 })
190β
191 it('TData should have undefined in the union when initialData is NOT provided', () => {
192 const { data } = useQuery(() => ({
193 queryKey: queryKey(),
194 queryFn: () => ({ wow: true }),
195 }))
196β
197 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
198 })
199β
200 it('TData should have undefined in the union when initialData is provided as a function which can return undefined', () => {
201 const { data } = useQuery(() => ({
202 queryKey: queryKey(),
203 queryFn: () => ({ wow: true }),
204 initialData: () => undefined as { wow: boolean } | undefined,
205 }))
206β
207 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
208 })
209 })
210β
211 describe('Query key overload', () => {
212 it('TData should always be defined when initialData is provided', () => {
213 const { data } = useQuery(() => ({
214 queryKey: queryKey(),
215 queryFn: () => ({ wow: true }),
216 initialData: { wow: true },
217 }))
218β
219 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
220 })
221β
222 it('TData should have undefined in the union when initialData is NOT provided', () => {
223 const { data } = useQuery(() => ({
224 queryKey: queryKey(),
225 queryFn: () => ({ wow: true }),
226 }))
227β
228 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
229 })
230 })
231β
232 describe('Query key and func', () => {
233 it('TData should always be defined when initialData is provided', () => {
234 const { data } = useQuery(() => ({
235 queryKey: queryKey(),
236 queryFn: () => ({ wow: true }),
237 initialData: { wow: true },
238 }))
239β
240 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
241 })
242β
243 it('TData should have undefined in the union when initialData is NOT provided', () => {
244 const { data } = useQuery(() => ({
245 queryKey: queryKey(),
246 queryFn: () => ({ wow: true }),
247 }))
248β
249 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
250 })
251 })
252 })
253β
254 describe('generic indexed access TData', () => {
255 // https://github.com/TanStack/query/issues/9937
256 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
257 enum DataType {
258 Account = 'account',
259 Product = 'product',
260 }
261β
262 interface Account {
263 name: string
264 }
265 interface Product {
266 code: string
267 }
268β
269 type DataTypeToEntity = {
270 [DataType.Account]: Account
271 [DataType.Product]: Product
272 }
273β
274 const getData = <TDataType extends DataType>(
275 _dataType: TDataType,
276 ): Promise<DataTypeToEntity[TDataType]> =>
277 Promise.resolve({} as DataTypeToEntity[TDataType])
278β
279 const getLabel = <TDataType extends DataType>(
280 _dataType: TDataType,
281 _data: DataTypeToEntity[TDataType],
282 ) => 'test'
283β
284 function Test<TDataType extends DataType>(props: {
285 dataType: TDataType
286 }) {
287 const { data } = useQuery(() => ({
288 queryKey: ['test'],
289 queryFn: () => getData(props.dataType),
290 }))
291β
292 // Regression guard: this call must compile. With the previous
293 // hand-rolled NoInfer, `data` failed to flow back into the generic
294 // indexed-access parameter `DataTypeToEntity[TDataType]`.
295 return data ? getLabel(props.dataType, data) : null
296 }
297β
298 expectTypeOf(Test).toBeFunction()
299 })
300 })
301})