Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2import { queryKey } from '@tanstack/query-test-utils'
3import { useQuery } from '../useQuery'
4import { queryOptions } from '../queryOptions'
5import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
6β
7describe('useQuery', () => {
8 const key = queryKey()
9β
10 // unspecified query function should default to unknown
11 const noQueryFn = useQuery({ queryKey: key })
12 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
13 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
14β
15 // it should infer the result type from the query function
16 const fromQueryFn = useQuery({ queryKey: key, queryFn: () => 'test' })
17 expectTypeOf(fromQueryFn.data).toEqualTypeOf<string | undefined>()
18 expectTypeOf(fromQueryFn.error).toEqualTypeOf<Error | null>()
19 expectTypeOf(fromQueryFn).not.toHaveProperty('promise')
20β
21 // it should be possible to specify the result type
22 const withResult = useQuery<string>({
23 queryKey: key,
24 queryFn: () => 'test',
25 })
26 expectTypeOf(withResult.data).toEqualTypeOf<string | undefined>()
27 expectTypeOf(withResult.error).toEqualTypeOf<Error | null>()
28β
29 // it should be possible to specify the error type
30 const withError = useQuery<string, Error>({
31 queryKey: key,
32 queryFn: () => 'test',
33 })
34 expectTypeOf(withError.data).toEqualTypeOf<string | undefined>()
35 expectTypeOf(withError.error).toEqualTypeOf<Error | null>()
36β
37 // it should provide the result type in the configuration
38 useQuery({
39 queryKey: [key],
40 queryFn: () => Promise.resolve(true),
41 })
42β
43 // it should be possible to specify a union type as result type
44 const unionTypeSync = useQuery({
45 queryKey: key,
46 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
47 })
48 expectTypeOf(unionTypeSync.data).toEqualTypeOf<'a' | 'b' | undefined>()
49 const unionTypeAsync = useQuery<'a' | 'b'>({
50 queryKey: key,
51 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
52 })
53 expectTypeOf(unionTypeAsync.data).toEqualTypeOf<'a' | 'b' | undefined>()
54β
55 // should error when the query function result does not match with the specified type
56 // @ts-expect-error
57 useQuery<number>({ queryKey: key, queryFn: () => 'test' })
58β
59 // it should infer the result type from a generic query function
60 function queryFn<T = string>(): Promise<T> {
61 return Promise.resolve({} as T)
62 }
63β
64 const fromGenericQueryFn = useQuery({
65 queryKey: key,
66 queryFn: () => queryFn(),
67 })
68 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string | undefined>()
69 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
70β
71 type MyData = number
72 type MyQueryKey = readonly ['my-data', number]
73β
74 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
75 queryKey: [, n],
76 }) => {
77 return Promise.resolve(n + 42)
78 }
79β
80 useQuery({
81 queryKey: ['my-data', 100],
82 queryFn: getMyDataArrayKey,
83 })
84β
85 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
86 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
87 return Promise.resolve(Number(context.queryKey[0]) + 42)
88 }
89β
90 useQuery({
91 queryKey: ['1'],
92 queryFn: getMyDataStringKey,
93 })
94β
95 // it should handle query-functions that return Promise<any>
96 useQuery({
97 queryKey: key,
98 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
99 })
100β
101 // handles wrapped queries with custom fetcher passed as inline queryFn
102 const useWrappedQuery = <
103 TQueryKey extends [string, Record<string, unknown>?],
104 TQueryFnData,
105 TError,
106 TData = TQueryFnData,
107 >(
108 qk: TQueryKey,
109 fetcher: (
110 obj: TQueryKey[1],
111 token: string,
112 // return type must be wrapped with TQueryFnReturn
113 ) => Promise<TQueryFnData>,
114 options?: OmitKeyof<
115 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
116 'queryKey' | 'queryFn' | 'initialData'
117 >,
118 ) =>
119 useQuery({
120 queryKey: qk,
121 queryFn: () => fetcher(qk[1], 'token'),
122 ...options,
123 })
124 const testQuery = useWrappedQuery([''], () => Promise.resolve('1'))
125 expectTypeOf(testQuery.data).toEqualTypeOf<string | undefined>()
126β
127 // handles wrapped queries with custom fetcher passed directly to useQuery
128 const useWrappedFuncStyleQuery = <
129 TQueryKey extends [string, Record<string, unknown>?],
130 TQueryFnData,
131 TError,
132 TData = TQueryFnData,
133 >(
134 qk: TQueryKey,
135 fetcher: () => Promise<TQueryFnData>,
136 options?: OmitKeyof<
137 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
138 'queryKey' | 'queryFn' | 'initialData'
139 >,
140 ) => useQuery({ queryKey: qk, queryFn: fetcher, ...options })
141 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
142 Promise.resolve(true),
143 )
144 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
145β
146 it('should return the correct states for a successful query', () => {
147 const state = useQuery<string, Error>({
148 queryKey: key,
149 queryFn: () => Promise.resolve('test'),
150 })
151β
152 if (state.isPending) {
153 expectTypeOf(state.data).toEqualTypeOf<undefined>()
154 expectTypeOf(state.error).toEqualTypeOf<null>()
155 return <span>pending</span>
156 }
157β
158 if (state.isLoadingError) {
159 expectTypeOf(state.data).toEqualTypeOf<undefined>()
160 expectTypeOf(state.error).toEqualTypeOf<Error>()
161 return <span>{state.error.message}</span>
162 }
163β
164 expectTypeOf(state.data).toEqualTypeOf<string>()
165 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
166 return <span>{state.data}</span>
167 })
168β
169 describe('initialData', () => {
170 describe('Config object overload', () => {
171 it('should always define TData when initialData is provided as an object', () => {
172 const { data } = useQuery({
173 queryKey: queryKey(),
174 queryFn: () => ({ wow: true }),
175 initialData: { wow: true },
176 })
177β
178 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
179 })
180β
181 it('should define TData when passed through queryOptions', () => {
182 const options = queryOptions({
183 queryKey: queryKey(),
184 queryFn: () => {
185 return {
186 wow: true,
187 }
188 },
189 initialData: {
190 wow: true,
191 },
192 })
193 const { data } = useQuery(options)
194β
195 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
196 })
197β
198 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
199 const options = queryOptions({
200 queryKey: queryKey(),
201 queryFn: () => Promise.resolve(1),
202 })
203β
204 const query = useQuery({
205 ...options,
206 select: (data) => data > 1,
207 })
208β
209 expectTypeOf(query.data).toEqualTypeOf<boolean | undefined>()
210 })
211β
212 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
213 const { data } = useQuery({
214 queryKey: queryKey(),
215 queryFn: () => {
216 return {
217 wow: true,
218 }
219 },
220 initialData: () => ({
221 wow: true,
222 }),
223 })
224β
225 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
226 })
227β
228 it('should have undefined in the TData union when initialData is NOT provided', () => {
229 const { data } = useQuery({
230 queryKey: queryKey(),
231 queryFn: () => {
232 return {
233 wow: true,
234 }
235 },
236 })
237β
238 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
239 })
240β
241 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
242 const { data } = useQuery({
243 queryKey: queryKey(),
244 queryFn: () => {
245 return {
246 wow: true,
247 }
248 },
249 initialData: () => undefined as { wow: boolean } | undefined,
250 })
251β
252 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
253 })
254β
255 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
256 const { data, isSuccess } = useQuery({
257 queryKey: queryKey(),
258 queryFn: () => {
259 return {
260 wow: true,
261 }
262 },
263 initialData: () => undefined as { wow: boolean } | undefined,
264 })
265β
266 if (isSuccess) {
267 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
268 }
269 })
270β
271 it('should preserve discriminated-union narrowing', () => {
272 type Result =
273 | { type: 'first'; first: string }
274 | { type: 'second'; second: string }
275β
276 const query = useQuery({
277 queryKey: queryKey(),
278 queryFn: (): Result => ({ type: 'first', first: 'a' }),
279 })
280β
281 const second = query.data?.type === 'first' ? undefined : query.data
282β
283 expectTypeOf(second).toEqualTypeOf<
284 { type: 'second'; second: string } | undefined
285 >()
286 })
287β
288 it('should not have undefined in data when initialData is provided', () => {
289 const { data } = useQuery({
290 queryKey: queryKey(),
291 initialData: 42,
292 })
293β
294 expectTypeOf(data).toEqualTypeOf<number>()
295 })
296 })
297β
298 describe('custom hook', () => {
299 it('should allow custom hooks using UseQueryOptions', () => {
300 type Data = string
301β
302 const useCustomQuery = (
303 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
304 ) => {
305 return useQuery({
306 ...options,
307 queryKey: queryKey(),
308 queryFn: () => Promise.resolve('data'),
309 })
310 }
311β
312 const { data } = useCustomQuery()
313β
314 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
315 })
316 })
317β
318 describe('structuralSharing', () => {
319 it('should be able to use structuralSharing with unknown types', () => {
320 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
321 useQuery({
322 queryKey: queryKey(),
323 queryFn: () => 5,
324 structuralSharing: (oldData, newData) => {
325 expectTypeOf(oldData).toBeUnknown()
326 expectTypeOf(newData).toBeUnknown()
327 return newData
328 },
329 })
330 })
331 })
332 })
333β
334 describe('generic indexed access TData', () => {
335 // https://github.com/TanStack/query/issues/9937
336 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
337 enum DataType {
338 Account = 'account',
339 Product = 'product',
340 }
341β
342 interface Account {
343 name: string
344 }
345 interface Product {
346 code: string
347 }
348β
349 type DataTypeToEntity = {
350 [DataType.Account]: Account
351 [DataType.Product]: Product
352 }
353β
354 const getData = <TDataType extends DataType>(
355 _dataType: TDataType,
356 ): Promise<DataTypeToEntity[TDataType]> =>
357 Promise.resolve({} as DataTypeToEntity[TDataType])
358β
359 const getLabel = <TDataType extends DataType>(
360 _dataType: TDataType,
361 _data: DataTypeToEntity[TDataType],
362 ) => 'test'
363β
364 // oxlint-disable-next-line @eslint-react/no-nested-component-definitions
365 function Test<TDataType extends DataType>(props: {
366 dataType: TDataType
367 }) {
368 const { data } = useQuery({
369 queryKey: ['test'],
370 queryFn: () => getData(props.dataType),
371 })
372β
373 // Regression guard: this call must compile. With the previous
374 // hand-rolled NoInfer, `data` failed to flow back into the generic
375 // indexed-access parameter `DataTypeToEntity[TDataType]`.
376 return data ? getLabel(props.dataType, data) : null
377 }
378β
379 expectTypeOf(Test).toBeFunction()
380 })
381 })
382})