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:
When I trigger the mutation by doing :
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.
6 Replies
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 mutationOh, thanks a lot. So I do need to do this manually after every mutation?
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
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
this is also a way to do it https://trpc.io/docs/v10/useContext#invalidate-full-cache-on-every-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...
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