-
Hi! I am working on a project where I want to receive continuous updates via websocket connection using RTK Query streaming. It is working great for me outside of the fact that it seems to require me to make a http request to fetch initial data before accepting to update this data via the websocket. From my understanding reading the docs I should be able to just connect to a websocket initially and go from there, but it does not seem to accept this, and requires me to provide an url to the baseQuery for the initial fetch? If I let baseQuery point to the root url of the project, I get a parsing error when trying to connect. The code I am currently using, where I have set up an api for providing the data on export const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:8000",
}),
endpoints: (build) => ({
getClock: build.query<Time, void>({
query: () => "/",
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved }
) {
const ws = new WebSocket("ws://localhost:8888/time");
try {
await cacheDataLoaded;
const listener = (event: MessageEvent) => {
const data = JSON.parse(event.data);
updateCachedData(() => {
return data;
});
};
ws.addEventListener("message", listener);
} catch {
//...
}
await cacheEntryRemoved;
ws.close();
},
}),
}),
});
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Often ppl only want to receive updates via websocket and the initial value from the server, yes. So we showed the "most complex" scenario of mixing both.
Yes, you can find an example of that here: https://github.com/phryneas/cli-mqtt-chatclient/blob/main/src/api.ts |
Beta Was this translation helpful? Give feedback.
-
Hi!. basically, I need to have only one WebSocket connection for my entire app and subscribe or unsubscribe to the socket and based on the data I update the other API slice cached data.
|
Beta Was this translation helpful? Give feedback.
Often ppl only want to receive updates via websocket and the initial value from the server, yes. So we showed the "most complex" scenario of mixing both.
Yes, you can find an example of that here: https://github.com/phryneas/cli-mqtt-chatclient/blob/main/src/api.ts