How to refetch data for a query when a mutation is performed in a different component?

To give a quick explanation of what I’m trying to do, I’m creating a system where a user can request to join a group and then the admins can accept or decline the request. I've tried following the docs for invalidating a single query but it seems to not be working in my case. Component A is fetching the request status on the user side through a useQuery on one of my tRPC procedures. Component A (checking request status on user side)
import { api } from "~/utils/api";

const {
data: joinRequestStatus,
isLoading: isLoadingJoinRequestStatus,
refetch: refetchJoinRequestStatus,
} = api.leagueUserManagement.getJoinRequestStatus.useQuery(
{
leagueSlug: league.leagueSlug,
},

{
queryKey: [
"leagueUserManagement.getJoinRequestStatus",
{ leagueSlug: league.leagueSlug },
],
staleTime: 5 * (60 * 1000),
cacheTime: 10 * (60 * 1000),
}
);
import { api } from "~/utils/api";

const {
data: joinRequestStatus,
isLoading: isLoadingJoinRequestStatus,
refetch: refetchJoinRequestStatus,
} = api.leagueUserManagement.getJoinRequestStatus.useQuery(
{
leagueSlug: league.leagueSlug,
},

{
queryKey: [
"leagueUserManagement.getJoinRequestStatus",
{ leagueSlug: league.leagueSlug },
],
staleTime: 5 * (60 * 1000),
cacheTime: 10 * (60 * 1000),
}
);
Component B performs a mutation (accept or decline) on the admin side from one of my tRPC procedures and I want it to immediately update the request status that the user sees in Component A after the admin accepts or declines. Component B (declining the request on admin side)
import { api } from "~/utils/api";

const utils = api.useContext();

const { mutate: declineJoinRequest, isLoading: isLoadingDeclineJoinRequest } =
api.leagueUserManagement.declineJoinRequest.useMutation({
onSuccess: async () => {
toast({
title: "Success",
description: "Join request declined",
variant: "success",
});
await refetchJoinRequests();
await utils.leagueUserManagement.getJoinRequestStatus.invalidate();
},
onError: (error) => {
toast({
title: "Error",
description: error.message,
variant: "error",
});
},
});
import { api } from "~/utils/api";

const utils = api.useContext();

const { mutate: declineJoinRequest, isLoading: isLoadingDeclineJoinRequest } =
api.leagueUserManagement.declineJoinRequest.useMutation({
onSuccess: async () => {
toast({
title: "Success",
description: "Join request declined",
variant: "success",
});
await refetchJoinRequests();
await utils.leagueUserManagement.getJoinRequestStatus.invalidate();
},
onError: (error) => {
toast({
title: "Error",
description: error.message,
variant: "error",
});
},
});
AK
Alex / KATT 🐱258d 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...
W
WO257d ago
Thanks! I’m trying to use the useContext hook to access my queries and invalidate them in the code snippets above but it doesn’t seem to be working. I’ve tried changing my query cache time, stale time, removing the refetch function from it but still can’t get it to work properly
I
icy.icicle253d ago
I am also running into this issue. I try to do any of the .invalidate() functions using the context, but it doesn't cause a rerender in the other components. I tried .refetch() too. alex / KATT 's solution fixed the issue, but I am using firebase, and a full refresh of the data is not cost effective for me.
T
Typedef230d ago
@icy.icicle Hi, did you find a solution? having the same issue.
I
icy.icicle230d ago
@_typedef Not the most optimal solution, but check out what @alexkatt does: https://trpc.io/docs/client/react/useContext#invalidate-full-cache-on-every-mutation I hate it, but it will refetch every query on the page every time there is a mutation
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...
N
NeoBean230d ago
i believe an idea solution would be to be able to pass an array of dependencies. Dependencies can query keys / routers
T
Typedef230d ago
Yep this works but I really dont want to refetch all queries in the cache. Wait so your useContext doesnt work aswell?
More Posts
Trying to lazy init "createTRPCProxyClient"I'm trying to wrap `createTRPCProxyClient`, but having trouble with the generic. Maybe I'm just a TSGet query parameters in middlewareHi! I'm looking to perform authorization inside of middleware and I'm wondering how I can access thetrpc middlewarecan you help me to catch all Response Codes from fetch called via trpc #❓-helpMultiple React Providers?I'm trying to have multiple providers in the same react (they can't be merged w/ virtual routing). IcreateCaller from API NextJS (Pages Directory)Hi, i want to call the procedure I was created in nextJS API.. and I already look at the documentatiWhy transformer: superjson breaks the POST ?With all the GET request I do there seem to be no error, but as soon as I try sending a POST requesttrpc receiving undefinedHello, I am having a few problems with one of my TRPC endpoints not recieving the data sent through How do you invalidate queries in nextjs app?`experimental_createTRPCNextAppDirClient` don't seems to have the useContext so how do i invalidate Do tracked properties still work when using useSuspenseQuery?From the React Query docs: ```By default, access to properties will be tracked, and the component wiProcedure return types are getting inferred as anyHi, I just created a prisma + trpc backend which uses prisma-trpc-generator to generate trpc routersHey 👋I'm looking to use tRPC with app-router specifically with this setup; - My pages are RSC, and I wanHi ! I get this error when i trying to getUser : ❌ tRPC failed on user.getUser: UNAUTHORIZEDwhat is "use" keyword```ts const baseProcedure = t.procedure .input(z.object({ townName: z.string() })) .use((opts) =How to Type a Middleware factory?Lemme first show you what I want, so you can get the gist of it. (Consider me less experienced in tyDoes "enabled" in useInfiniteQuery work?I am trying to prevent the hook to fetch data using "enabled" parameter. It works in useQuery, but uHow to use NextJS tRPC client without hooks?I want to use the vanilla tRPC client in NextJS (both browser+server), but I can't because it doesn'"Fast Refresh" messing with my WebSocketServer in Next.js developmentI got my websockets up and running in **tRPC **+ **Next.js** with this code: ```js import { WebSockt3-turboHey anyone know how to integrate clerk into t3-turbo appavoiding used more hooks than previous renderI understand whats causing the error in my code, im checking if id is defined before calling useQuerHow would batching result in a single database query?On the `httpBatchStreamLink` docs it says that multiple query calls could result in a single databas