Get Query Key on Server
I'm following some recommended practices from one of the react query maintainers
@tkdodo
and want to invalidate queries from the server in a type-safe way. As a result of this I want to be able to get the query keys for queries on the server to properly invalidate them using a trpc subscription. Is there a clean way to feed the router definition into getQueryKey
?
At the moment what I'm doing is:
This is not in the react context and I don't really want to import react in order to get the query keySolution:Jump to solution
I wouldn’t couple the backend into the frontend state management by trying to dispatch the query key. Instead dispatch a message relevant to your business logic, and on the frontend turn that into a query key for invalidation and optimistic updates, you’ll have a better time
8 Replies
Where did he recommend this? I think this is pretty far from a good practice. Use the onSuccess callback on the client
Using WebSockets with React Query
A step-by-step guide on how to make real-time notifications work with react-query
Oh thanks, I see better what you’re trying to achieve now
Solution
I wouldn’t couple the backend into the frontend state management by trying to dispatch the query key. Instead dispatch a message relevant to your business logic, and on the frontend turn that into a query key for invalidation and optimistic updates, you’ll have a better time
So dispatch the entity type and id, or just the whole entity, or a general message to invalidate a bunch of stuff
Yeah, the primary issue is that I don't actually want to handle partial updates (with data) as you can't really protect trpc websocket connections with session.
I could theoretically publish events per type e.g. invalidateEvent, eventId
The react work around does work at the moment. I'll do some more testing
but because my frontend state is so closely tied to my backend state through trpc-react I'm trying to keep it that way, extremely type safe