trpc query only once parameter is not null

New in T3 stack so forgive me if this is a noob question: I am trying to run a trpc query only if a user is logged in. The user id is part of the query parameter. const { data: sessionData } = useSession(); const cart = api.cart.getCart.useQuery({ userId: sessionData?.user?.id }); Normally I would just add sessionData to the query key but there is no option for that here right? Or is there?
7 Replies
stanisław
stanisław2y ago
enabled in useQuery options @marvintherain
barry
barry2y ago
seems more like a protectedProcedure would make more sense here
danmrkw
danmrkwOP2y ago
I have found the options 🙂 const cart = api.cart.getCart.useQuery({ userId: sessionData?.user?.id },{queryKey: ["cart", "getCart", sessionData],}); The procedure is actually protected but it seemed inefficient to me to generate network requests destined to fail
Brenner
Brenner2y ago
use the enabled: !!sessionData option
Piotrek
Piotrek2y ago
Use the enabled option: const { data: sessionData } = useSession(); const cart = api.cart.getCart.useQuery({ userId: sessionData?.user?.id }, { enabled: !!sessionData });
barry
barry2y ago
why double call just do protected procedure
danmrkw
danmrkwOP2y ago
thanks for your comments this helps a lot 👍
Want results from more Discord servers?
Add your server