TRPC mutates the data in the backend but doesn't rerender on the client? (shows stale data)

I have a very simple useQuery call and a very simple mutation I am doing:
const mutation = trpc.item.update.useMutation();

const { data, isLoading } = trpc.item.getAll.useQuery();
const mutation = trpc.item.update.useMutation();

const { data, isLoading } = trpc.item.getAll.useQuery();
When I trigger the mutation by doing :
mutation.mutate({ id: "cl91hleaq0000z06l46ln7yr5", text: "I am mutated" })
mutation.mutate({ id: "cl91hleaq0000z06l46ln7yr5", text: "I am mutated" })
it does update the data in the backend. However, my front-end doesn't re-render and it's still showing my stale data until I refresh the page. Not sure what's going on.
<pre>
{JSON.stringify(data, null, 4)}
{/* showing stale data until refresh, or windows refocus etc. */}
</pre>
<pre>
{JSON.stringify(data, null, 4)}
{/* showing stale data until refresh, or windows refocus etc. */}
</pre>
6 Replies
Piotrek
Piotrek2y ago
You have to tell tRPC to refetch the data by using refetch on the useQuery ({ data, isLoading, refetch } = ...useQuery()) You can call it eg. In onSuccess method of the mutation
plyglt
plyglt2y ago
Oh, thanks a lot. So I do need to do this manually after every mutation?
Piotrek
Piotrek2y ago
Yeah, you somehow have to tell tRPC when to refetch the data React query has no way of knowing when you want to do it and when something in the db changes
cje
cje2y ago
Read through the react query docs A common pattern is to invalidate when the mutation succeeds There’s other fancy stuff you can do beyond that, but that’s the most basic/common pattern It’s because there is no way for query/tRPC to know which procedures deal with which things in the database
zenith
zenith2y 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...
zenith
zenith2y ago
I think it's one of those things that aren't that bad in practice but feel kinda bad at the very least TRPC will batch the queries into one request, but it will increase database reads and if you have LOTS of data on a particular route might not be the best idea
Want results from more Discord servers?
Add your server