Fire trpc useQuery only when a callback is called

I have kind of a weird use case. I would like to run a trpc useQuery() only when a callback is called. This callback is triggered by a push notification so I don't want the query to update on its own, only when the callback fires. How can i do this?
2 Replies
Tom
Tom14mo ago
I currently have the following:
const trpcUtils = trpc.useContext();
const tournamentQuery = trpc.tournaments.getTournamentInternal.useQuery(
{ tournamentID: id ?? "", version: 0 },
{ enabled: !!id, keepPreviousData: true }
);

useEffect(() => {
/* prevents errors when id is empty due to SSR */
if (!id) return;

const unsubscribe = registerTournamentChangedListener(id, (v) => {
trpcUtils.tournaments.getTournamentInternal.invalidate({ tournamentID: id, version: v });
});
return () => {
unsubscribe();
};
});
const trpcUtils = trpc.useContext();
const tournamentQuery = trpc.tournaments.getTournamentInternal.useQuery(
{ tournamentID: id ?? "", version: 0 },
{ enabled: !!id, keepPreviousData: true }
);

useEffect(() => {
/* prevents errors when id is empty due to SSR */
if (!id) return;

const unsubscribe = registerTournamentChangedListener(id, (v) => {
trpcUtils.tournaments.getTournamentInternal.invalidate({ tournamentID: id, version: v });
});
return () => {
unsubscribe();
};
});
this mostly works but i would like to prevent the 'refresh when changing windows' behavior
higgsboz
higgsboz13mo ago
You should be able to accomplish this using 2 things. 1. Set enabled: false in the query options 2. Call tournamentQuery.refetch in your useEffect when your condition is true
const trpcUtils = trpc.useContext();
const {data, refetch} = trpc.tournaments.getTournamentInternal.useQuery(
{ tournamentID: id ?? "", version: 0 },
{ enabled: false, keepPreviousData: true }
);

useEffect(() => {
/* prevents errors when id is empty due to SSR */
if (!id) return;

const unsubscribe = registerTournamentChangedListener(id, (v) => {
refetch()
});
return () => {
unsubscribe();
};
});
const trpcUtils = trpc.useContext();
const {data, refetch} = trpc.tournaments.getTournamentInternal.useQuery(
{ tournamentID: id ?? "", version: 0 },
{ enabled: false, keepPreviousData: true }
);

useEffect(() => {
/* prevents errors when id is empty due to SSR */
if (!id) return;

const unsubscribe = registerTournamentChangedListener(id, (v) => {
refetch()
});
return () => {
unsubscribe();
};
});