Clarification/Feature Request: WebSocket lifecycle management in RTK Query streaming endpoints #4963
Replies: 1 comment 1 reply
-
I don't think we have any recommendation here, because that's ultimately out of the scope of RTKQ itself. RTKQ is really a promise/async status tracking library. That matches both the HTTP request/response model, and most core data fetching needs. As you've noted, you can use the lifecycle handling to initiate various streaming/websocket methods that are tied to the cache entry lifetimes, but that is something you're writing yourself separately. RTKQ has no notion of "there's a long-lived connection associated with this cache entry" - it just knows the status of the most recent promise associated with the cache entry, request-wise. Given that, I'd say it's also up to you to decide where and how you want to track websocket status - it's not something that's built in or that we have an opinion on, especially since it's going to be unique to your app. (I could very vaguely imagine (ab-)using another cache entry to represent the status of a websocket connection somehow, but mostly in the sense of the status tracking aspect itself.) |
Beta Was this translation helpful? Give feedback.
-
Summary
As far as I can tell, RTK Query doesn’t currently provide a way to reflect disconnection or failure of a long-lived data stream (like a WebSocket) in the
useQuery
hook afterqueryFn
has fulfilled successfully. As a result,isSuccess
remainstrue
even if the WebSocket fails to connect or closes unexpectedly. I’m looking for clarification or guidance on how to track and represent WebSocketopen
,close
anderror
states with RTK Query.Problem
If I understand the docs correctly, RTK Query recommends:
queryFn
→ for initial snapshot via HTTPonCacheEntryAdded
→ for subscribing to real-time updates (e.g. WebSocket)This works well initially — but it’s unclear how to handle the case where the WebSocket fails to connect or is closed unexpectedly by the server. The result is that
useQuery()
continues reportingisSuccess: true
, even though the real-time stream is broken, leading to misleading UI state.Current Workaround
The only solution I’ve found is to manage WebSocket connection state separately (e.g., in a Redux slice), and expose that to components alongside the
useQuery()
result. This works, but feels like duplicating effort, especially sinceuseQuery
already hasisLoading
,isSuccess
, andisError
built-in.Ideally
onCacheEntryAdded
would expose some kind of callback for updating these states.Question
Is there a recommended way to reflect WebSocket
open
,close
anderror
in theuseQuery
state — for example, by settingisError: true
or updating theerror
field after the stream fails?Beta Was this translation helpful? Give feedback.
All reactions