Skip to content

Add support for handling initial data coming from within onCacheEntryAdded #5054

@croraf

Description

@croraf

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions