Add support for handling initial data coming from within onCacheEntryAdded
When using websocket state updates we want to use a model with the onCacheEntryAdded (described in the docs) .
export const apiBackendWebsocket = createApi({
reducerPath: "backendWebsocket",
baseQuery: fakeBaseQuery(), // We don't need a base query since we're not making HTTP requests
endpoints: (builder) => ({
// This query endpoint will manage the websocket
getCases: builder.query<Item[], void>({
// `queryFn` can be use to fetch the initial data.
queryFn: () => ({ data: null }), // TODO PROBLEM
// This is run when there on no subscription and the subscription happens
async onCacheEntryAdded(_arg, { updateCachedData, cacheEntryRemoved, }) {
const socket = io(`${hostname}`, {
transports: ["websocket"],
auth: {token: "test_token" },
});
socket.on("cases", (payload: Item[]) => {
updateCachedData((draft) => {
//
});
});
// Wait for the component to unmount to clean up the socket connection
await cacheEntryRemoved;
socket.disconnect();
},
keepUnusedDataFor: 3600,
}),
}),
});
But this poses a problem if we want to have the initial data getting streamed with the websocket. (This is beneficial to avoid any concurrency issues that might happen if the data comes both from the REST and from the webscoket)
In that case we want to have isLoading and isFetching status to true before the initial data comes from the websocket.
Can the RTK Query API be updated somehow to support this model?
I don't think we have any desire to make changes here.
The closest I can think of would be dispatching api.util.upsertQueryEntries() to force the entry to exist.
Alternately, you could type the data for the cache entry as MyData | null, but then you'd have to do null checks everywhere.
Conceptually, what would actually expect here in terms of behavior and types? What would it mean, data-and-status-flags-wise, for there to be a cache entry with "no initial data"? How would adding that cache entry get triggered in the first place?