tRPCttRPC
Powered by
shanksxzS
tRPC•14mo ago•
1 reply
shanksxz

Optimizing Global State Updates for Mutations Across Multiple Query Keys in tRPC with React Query

I'm using tRPC with React Query in my app, and I need some advice. I have a mutation (e.g., toggleLike) that updates a specific field (hasLiked) for posts. The mutation works fine, and I'm using optimistic updates to reflect the changes immediately in the UI.

Here's the challenge:
I need this hasLiked field to update consistently across multiple query keys, such as getLatest and getTrending, whenever the mutation is triggered. Right now, I have to manually update each query like this:

utils.post.getLatest.setData(...);  
utils.post.getTrending.setData(...);
utils.post.getLatest.setData(...);  
utils.post.getTrending.setData(...);


This approach works, but it feels repetitive and hard to scale. Is there a way to generalize this behavior so that I can update the hasLiked field across all relevant queries in one go? Maybe something like utils.setFields or a custom utility?
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Getting global query loading state on client (react)
Mighty EightMMighty Eight / ❓-help
9mo ago
trpc subscription with react-query
kamamaKkamama / ❓-help
3y ago
Optimistic updates using tRPC 11 with TanStack React Query 5
editEedit / ❓-help
9mo ago