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();
}

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.

Further reading

Problem with a question

State Management · Senior · question 51

Test yourself

Take the State Management · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz