Invalidating a single part of a larger query

I am fetching data as such const postQuery = api.primaryRouter.getPosts.useQuery({}); and rendering as a list. I would like to invalidate JUST a single ID, this is possible via scenario #3 here https://trpc.io/docs/reactjs/usecontext#invalidating-across-whole-routers For example, if I later update one of the posts, I update then fetch just the updated post as follows -
userMutation.mutate(
{
id,
increment,
},
{
onSuccess: () => {
console.log("success");
utils.primaryRouter.getPosts
.invalidate({
id,
})
.catch((err) => {
console.log(err);
});
},
}
);
userMutation.mutate(
{
id,
increment,
},
{
onSuccess: () => {
console.log("success");
utils.primaryRouter.getPosts
.invalidate({
id,
})
.catch((err) => {
console.log(err);
});
},
}
);
Now the problem is, as I never used an ID to fetch posts to begin with, that query doesn't get invalidated (as the tag is different). I'm not entirely sure what the correct way to optimally update just a single record in a "fetch all" type query is?
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...
7 Replies
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Yoers
YoersOP•2y ago
Thanks for the response, so I understand why it doesn't work and I do indeed just invalidate the entire query for now. However I would like to understand how I can implement such a solution (whereby only the post I care about re-loads) Any advice there would be much appreciated 🙂
cje
cje•2y ago
it's not possible in the way you want you could do something hacky like return the changed post from the mutation and manually update the cache in onSuccess but i wouldn't recommend it
Yoers
YoersOP•2y ago
Ok thanks @cje , perhaps an optimization i'll leave out for now. You presumably don't recommend this because the chance your local source will be out of sync with the server?
cje
cje•2y ago
Yea Doing cache manipulation yourself is a huge foot gun Http requests are cheap, incorrect data is expensive (usually)
jingleberry
jingleberry•2y ago
I think you’ve run into one of the limitations surrounding React Query (which is what trpc uses under the hood) Since it uses a document rather than a normalized caching strategy you can’t simply update a single post if your query is meant to fetch multiple posts Refetching all posts or manually updating the cache are your best solutions here
cje
cje•2y ago
previous ways of managing server state had options for this, but we moved away from them because everyone hated managing the cache
Want results from more Discord servers?
Add your server