How to make a trpc request wait on another hook

I basically have a state that is populated from a query param then an API call (i used context before and now jotai) but it is critical to populate that state first before issuing a following trpc call that will fetch something.
// store.ts
export const currentGuildAtom = atom<DiscordGuildProfile | null>(null);

// page.tsx
const guild = useAtomValue(currentGuildAtom);

const { data: textChannels } =
trpc.guildChannels.getGuildTextChannels.useQuery({
guildId: guild.id,
});
// store.ts
export const currentGuildAtom = atom<DiscordGuildProfile | null>(null);

// page.tsx
const guild = useAtomValue(currentGuildAtom);

const { data: textChannels } =
trpc.guildChannels.getGuildTextChannels.useQuery({
guildId: guild.id,
});
I need to initialize the state at null since it could actually be that where i manage that case by redirecting elsewhere. but if I hit this page, the state is populated but too early for trpc to handle it, and since hooks cannot live inside useEffect, I dont see a way to handle this, is there a way to suspend the trpc hook until I validate that guild is not null? or another workaround?
7 Replies
Shoodey
Shoodey•2y ago
For now, I made the trpc endpoint accept a string | null and do nothing if its null, soo :/
rocawear
rocawear•2y ago
Disabling/Pausing Queries | TanStack Query Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option. When enabled is false:
Shoodey
Shoodey•2y ago
Thanks! i see, and then refetch within the useEffect?
rocawear
rocawear•2y ago
Make it so it's disabled if there is no value so it would be enabled: !!guild So when there is value it runs
Shoodey
Shoodey•2y ago
it knew! 😛
rocawear
rocawear•2y ago
🔥🔥
Shoodey
Shoodey•2y ago
thanks a lot mate, will give it a shot, seems like i should dedicate some time to read/learn react query 🙂
Want results from more Discord servers?
Add your server