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