T
TanStack3y ago
provincial-silver

WebSocket integration

Hi All, Have a question to ask about a particular use case, I'm currently looking to get WebSockets working alongside TanStack query. I get exactly how to update the existing query data via mutate or invalidate so this side make sense. Thanks to this great post: https://tkdodo.eu/blog/using-web-sockets-with-react-query However In my use case I need to subscribe to multiple topics and plan to only subscribe when each useQuery is used/mounted. So plan send subscribe and unsubscribe messages for each topic on mount/dismount of a particular useQuery(). However in this scenario where the same query is mounted more than once then this will lead to issues as I will need to keep track of how many times its currently mounted and by which component its being used. And therefore only tigger the topic unsubscribe when the last component is dismounted, to actually stop listening to changes about a particularly useQuery. I would be extremely surprised if I'm the very first person to have this use case . I've tried a google to see if there are any libraries out there to keep track of topic subscriptions but seem to hit a blank, either that or my search terms are just too generic. Any existing solutions/pointers before start writing a custom implementation?
Using WebSockets with React Query
A step-by-step guide on how to make real-time notifications work with react-query
4 Replies
noble-gold
noble-gold3y ago
I'm having a similar issue. I currently wrap my useQuery calls in another hook, like useCommentThread, which sets up the necessary WebSocket stuff in a useEffect(). However, if I want to do this with useQueries, I'd need to move that logic onto the query itself, rather than useEffect.
provincial-silver
provincial-silverOP3y ago
I managed to solve my issue, I can provide a snippet tomorrow of how I fix it for the result I wanted
optimistic-gold
optimistic-gold3y ago
@j3tto Any update on that snippet?
optimistic-gold
optimistic-gold3y ago
I'm a little late to the party but you can subscribe to changes in the client itself. https://tanstack.com/query/latest/docs/react/reference/QueryCache#querycachesubscribe
QueryCache | TanStack Query Docs
The QueryCache is the storage mechanism for TanStack Query. It stores all the data, meta information and state of queries it contains. Normally, you will not interact with the QueryCache directly and instead use the QueryClient for a specific cache.

Did you find this page helpful?