Refetching tRPC query after mutation from a child

Hey, this might be a pretty noob tRPC question as I'm quite new to the whole tRPC + TanStack Query setup. I have a component NotificationPanel which uses tRPC to query unread notifications for a given user. Once it fetches those notifications, it renders multiple NotificationItem elements and passes the notification object to them. The NotificationItem has a x button which uses tRPC mutate to mark itself READ. At this point, i would like the parent NotificationPanel component to re-fetch unread notifications for the user, but am not sure how to achieve this. I tried digging through TanStack Query docs but didn't find much. On Google, most articles are quite outdated and that approach doesn't seem to work well with tRPC's wrapper around TanStack Query. Any ideas how to achieve this?
5 Replies
haardik | LearnWeb3
One way that works right now is by extracting the refetch function from useQuery and passing it down to each of the children. Then, onSuccess of the mutation, I can call refetch This works, but I wonder if there's a better way?
cje
cje2y ago
youre probably looking for useContext
cje
cje2y ago
useContext | tRPC
useContext is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via @trpc/react-query. These helpers are actually thin wrappers around @tanstack/react-query's queryClient methods. If you want more in-depth information about options and usage patterns for useContext helpers than what we provide...
cje
cje2y ago
you can use that to invalidate or refetch in the onSuccess of your mutation without having to pass the actual refetch function around
haardik | LearnWeb3
Oooh thank you! This works beautifully @cje for those who might stumble upon this later, I did something like this: In NotificationItem (the child)
const utils = trpc.useContext();
const markReadMutation = trpc.notifications.markRead.useMutation({
onSuccess: () => utils.notifications.unread.refetch()
})
const utils = trpc.useContext();
const markReadMutation = trpc.notifications.markRead.useMutation({
onSuccess: () => utils.notifications.unread.refetch()
})
Want results from more Discord servers?
Add your server