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 type MyData = number
73 type MyQueryKey = readonly ['my-data', number]
74β
75 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
76 queryKey: [, n],
77 }) => {
78 return n + 42
79 }
80β
81 useQuery(() => ({
82 queryKey: ['my-data', 100] as const,
83 queryFn: getMyDataArrayKey,
84 }))
85β
86 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
87 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
88 return Number(context.queryKey[0]) + 42
89 }
90β
91 useQuery(() => ({
92 queryKey: ['1'] as ['1'],
93 queryFn: getMyDataStringKey,
94 }))
95β
96 // it should handle query-functions that return Promise<any>
97 useQuery(() => ({
98 queryKey: key,
99 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
100 }))
101β
102 // handles wrapped queries with custom fetcher passed as inline queryFn
103 const useWrappedQuery = <
104 TQueryKey extends [string, Record<string, unknown>?],
105 TQueryFnData,
106 TError,
107 TData = TQueryFnData,
108 >(
109 qk: TQueryKey,
110 fetcher: (
111 obj: TQueryKey[1],
112 token: string,
113 // return type must be wrapped with TQueryFnReturn
114 ) => Promise<TQueryFnData>,
115 options?: OmitKeyof<
116 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
117 'queryKey' | 'queryFn' | 'initialData',
118 'safely'
119 >,
120 ) =>
121 useQuery(() => ({
122 queryKey: qk,
123 queryFn: () => fetcher(qk[1], 'token'),
124 ...options,
125 }))
126 const test = useWrappedQuery([''], () => Promise.resolve('1'))
127 expectTypeOf(test.data).toEqualTypeOf<string | undefined>()
128β
129 // handles wrapped queries with custom fetcher passed directly to useQuery
130 const useWrappedFuncStyleQuery = <
131 TQueryKey extends [string, Record<string, unknown>?],
132 TQueryFnData,
133 TError,
134 TData = TQueryFnData,
135 >(
136 qk: TQueryKey,
137 fetcher: () => Promise<TQueryFnData>,
138 options?: OmitKeyof<
139 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
140 'queryKey' | 'queryFn' | 'initialData',
141 'safely'
142 >,
143 ) => useQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
144 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
145 Promise.resolve(true),
146 )
147 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
148β
149 it('should return the correct states for a successful query', () => {
150 const state = useQuery<string, Error>(() => ({
151 queryKey: key,
152 queryFn: () => Promise.resolve('test'),
153 }))
154β
155 if (state.isPending) {
156 expectTypeOf(state.data).toEqualTypeOf<undefined>()
157 expectTypeOf(state.error).toEqualTypeOf<null>()
158 } else if (state.isLoadingError) {
159 expectTypeOf(state.data).toEqualTypeOf<undefined>()
160 expectTypeOf(state.error).toEqualTypeOf<Error>()
161 } else {
162 expectTypeOf(state.data).toEqualTypeOf<string>()
163 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
164 }
165 })
166β
167 describe('initialData', () => {
168 describe('Config object overload', () => {
169 it('should always define TData when initialData is provided as an object', () => {
170 const { data } = useQuery(() => ({
171 queryKey: queryKey(),
172 queryFn: () => ({ wow: true }),
173 initialData: { wow: true },
174 }))
175β
176 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
177 })
178β
179 it('should define TData when passed through queryOptions', () => {
180 const options = queryOptions({
181 queryKey: queryKey(),
182 queryFn: () => ({ wow: true }),
183 initialData: { wow: true },
184 })
185 const { data } = useQuery(() => options)
186β
187 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
188 })
189β
190 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
191 const { data } = useQuery(() => ({
192 queryKey: queryKey(),
193 queryFn: () => ({ wow: true }),
194 initialData: () => ({ wow: true }),
195 }))
196β
197 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
198 })
199β
200 it('should have undefined in the TData union when initialData is NOT provided', () => {
201 const { data } = useQuery(() => ({
202 queryKey: queryKey(),
203 queryFn: () => ({ wow: true }),
204 }))
205β
206 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
207 })
208β
209 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
210 const { data } = useQuery(() => ({
211 queryKey: queryKey(),
212 queryFn: () => ({ wow: true }),
213 initialData: () => undefined as { wow: boolean } | undefined,
214 }))
215β
216 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
217 })
218 })
219β
220 describe('Query key overload', () => {
221 it('should always define TData when initialData is provided', () => {
222 const { data } = useQuery(() => ({
223 queryKey: queryKey(),
224 queryFn: () => ({ wow: true }),
225 initialData: { wow: true },
226 }))
227β
228 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
229 })
230β
231 it('should have undefined in the TData union when initialData is NOT provided', () => {
232 const { data } = useQuery(() => ({
233 queryKey: queryKey(),
234 queryFn: () => ({ wow: true }),
235 }))
236β
237 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
238 })
239 })
240β
241 describe('Query key and func', () => {
242 it('should always define TData when initialData is provided', () => {
243 const { data } = useQuery(() => ({
244 queryKey: queryKey(),
245 queryFn: () => ({ wow: true }),
246 initialData: { wow: true },
247 }))
248β
249 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
250 })
251β
252 it('should have undefined in the TData union when initialData is NOT provided', () => {
253 const { data } = useQuery(() => ({
254 queryKey: queryKey(),
255 queryFn: () => ({ wow: true }),
256 }))
257β
258 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
259 })
260 })
261 })
262β
263 describe('generic indexed access TData', () => {
264 // https://github.com/TanStack/query/issues/9937
265 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
266 enum DataType {
267 Account = 'account',
268 Product = 'product',
269 }
270β
271 interface Account {
272 name: string
273 }
274 interface Product {
275 code: string
276 }
277β
278 type DataTypeToEntity = {
279 [DataType.Account]: Account
280 [DataType.Product]: Product
281 }
282β
283 const getData = <TDataType extends DataType>(
284 _dataType: TDataType,
285 ): Promise<DataTypeToEntity[TDataType]> =>
286 Promise.resolve({} as DataTypeToEntity[TDataType])
287β
288 const getLabel = <TDataType extends DataType>(
289 _dataType: TDataType,
290 _data: DataTypeToEntity[TDataType],
291 ) => 'test'
292β
293 function Test<TDataType extends DataType>(props: {
294 dataType: TDataType
295 }) {
296 const { data } = useQuery(() => ({
297 queryKey: ['test'],
298 queryFn: () => getData(props.dataType),
299 }))
300β
301 // Regression guard: this call must compile. With the previous
302 // hand-rolled NoInfer, `data` failed to flow back into the generic
303 // indexed-access parameter `DataTypeToEntity[TDataType]`.
304 return data ? getLabel(props.dataType, data) : null
305 }
306β
307 expectTypeOf(Test).toBeFunction()
308 })
309 })
310})