Vue useQuery type issue #5930
Replies: 3 comments 3 replies
-
The type error in your code might stem from a type deficiency within If it is, I'm willing to attempt to fix this issue. type User = any;
export function useUser(
userId: MaybeRefOrGetter<number>,
options?: UseQueryOptions<User, AxiosError, User, readonly [string, MaybeRef<number>]>,
) {
return useQuery({
queryKey: ['user', toRef(userId)],
async queryFn({ queryKey }) {
const res = await fetch(`/api/user/${queryKey[1]}`);
return res.json();
},
...options,
});
} |
Beta Was this translation helpful? Give feedback.
-
Following your code example where const fetchUser = (userId: number) => fetch(`/api/user/${userId}`).then((res) => res.json());
type User = any;
export function useUser(
userId: MaybeRefOrGetter<number>,
options?: UseQueryOptions<User, AxiosError, User, readonly [string, MaybeRef<number>]>,
) {
return useQuery({
queryKey: ['user', toRef(userId)],
queryFn({ queryKey }) {
return fetchUser(queryKey[1]);
},
...options,
} satisfies typeof options);
}
We can work around this by wrapping |
Beta Was this translation helpful? Give feedback.
-
Just found this in the types: https://github.com/TanStack/query/blob/main/packages/vue-query/src/types.ts#L49 So it looks like as a workaround, this does work: const fetchUser = (userId: number) => fetch(`/api/user/${userId}`).then((res) => res.json());
type User = any;
export function useUser(
userId: MaybeRefOrGetter<number>,
options?: UseQueryOptions<User, AxiosError, User, readonly [string, number]>,
) {
return useQuery({
queryKey: computed(() => ['user', toValue(userId)]),
queryFn({ queryKey }) {
return fetchUser(queryKey[1]);
},
...options,
} satisfies typeof options);
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This might be a bug, or might be an issue with my code - I'm not really sure.
I'm trying to wrap my
useQuery
calls with my own composables, but I'm struggling with the types:This gives me this error from
toRef(userId)
:However, changing the
TQueryKey
arg toreadonly [string, Ref<number>]
results in thequeryKey
having the incorrect type when passed to thequeryFn
.Am I doing something wrong or are the library's types incorrect?
Side note, the reason I'm doing this is so that I can hide all the
useMutation
cache invalidation logic and stuff like that in the composable file, but at the point of consumption still be able to specify my own refetch interval, callback functions etc with the correct types. This is a minimal example and doesn't make as much sense as my actual usage does!Beta Was this translation helpful? Give feedback.
All reactions