Redux
Advanced
RTK Query Lifecycle and Streaming
Use lifecycle callbacks for WebSocket updates, cache hydration, retries, and enterprise API resilience.
40 min
2 sections
rtk-query
websocket
lifecycle
resilience
1
2
01. Stream updates into cached queries
Section 1 of 2
Use onCacheEntryAdded when the server pushes updates after the initial query. This pattern fits live ticket queues, notification centers, trading dashboards, and audit monitors.
typescript
getTicketQueue: builder.query<Ticket[], { orgId: string; queueId: string }>({
query: ({ orgId, queueId }) =>
`/orgs/${orgId}/queues/${queueId}/tickets`,
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved }
) {
await cacheDataLoaded;
const socket = new WebSocket(
`wss://events.example.com/orgs/${arg.orgId}/queues/${arg.queueId}`
);
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data) as TicketEvent;
updateCachedData((draft) => {
const index = draft.findIndex((ticket) => ticket.id === message.ticket.id);
if (index >= 0) draft[index] = message.ticket;
else draft.unshift(message.ticket);
});
});
await cacheEntryRemoved;
socket.close();
},
})Back to Course