T
TanStack9mo ago
deep-jade

Is it possible to make reusable useQuery in composables?

Hi, I wanted to create custom hooks in composables like so:
import { useQuery } from "@tanstack/vue-query";
import { useAuthStore } from "../stores/useAuthStore";

export const useMe = () => {
const { isAuth } = useAuthStore();
const userClient = useUserClient();

return useQuery({
queryFn: () => userClient.getMe,
queryKey: [queryKeys.value.user.me],
enabled: isAuth.value,
});
};
import { useQuery } from "@tanstack/vue-query";
import { useAuthStore } from "../stores/useAuthStore";

export const useMe = () => {
const { isAuth } = useAuthStore();
const userClient = useUserClient();

return useQuery({
queryFn: () => userClient.getMe,
queryKey: [queryKeys.value.user.me],
enabled: isAuth.value,
});
};
but I get error [nuxt] [request error] [unhandled] [500] Cannot stringify a function Is there any possibility to make easy reusable hooks/functions to use in components without triggering this error?
1 Reply
eager-peach
eager-peach9mo ago
I think you're getting error for queryKey hashing but can you provide full stack trace? Custom hooks definitely worth creating for code reuse. Couple recommendations: 1. Options object passed into useQuery can be computed. Use it to preserve reactivity of queryKey. 2. enabled also supports reactive values. So you can declare enabled: isAuth and query will watch it internally when isAuth becomes truthy. Also it seems that your queryFn should be just queryFn: userClient.getMe. I also wrote an article on reactivity loss in composables I can recommend to check out https://paulau.dev/blog/common-mistakes-in-tanstack-query-and-vuejs-composition-api#losing-reactivity-in-custom-composable

Did you find this page helpful?