State Management · Senior · Question 51 of 75
How do you push WebSocket updates into an RTK Query cache entry?
async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {
await cacheDataLoaded;
const ws = new WebSocket(url);
ws.onmessage = (e) => updateCachedData((draft) => { draft.push(JSON.parse(e.data)); });
await cacheEntryRemoved;
ws.close();
}- ✓Correct answer: Use the endpoint's
onCacheEntryAddedlifecycle withupdateCachedData, closing the socket when the entry is removed - 2Dispatch a regular slice action from
ws.onmessageand copy data manually - 3Poll the endpoint every 100ms
Explanation
The socket lives exactly as long as some component subscribes to that cache entry, and updates go through Immer drafts like other cache updates.