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:
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?
2 replies