How to Update Cache Data from Middleware? #3633
-
Hey everyone, I'm working on creating a WebSocket connection using SignalR inside my middleware, and now I'm looking to update cache data. Can it be done? Need your insights and help on this! In the example below, I attempted to dispatch // signalRMiddleware.ts
let connection: HubConnection | null = null;
const createSignalRConnection = (getState: () => RootState) => {
const state = getState();
const { connectionHub } = state;
const internalToken = selectInternalToken(state);
const options: IHttpConnectionOptions = {
accessTokenFactory: () => internalToken,
};
return new HubConnectionBuilder()
.withUrl(`${connectionHub}`, options)
.withAutomaticReconnect()
.build();
};
const signalRMiddleware: Middleware =
({ getState, dispatch }) =>
(next) =>
(action) => {
if (action.type === startSignalRConnectionActionType) {
if (!connection || connection.state === HubConnectionState.Disconnected) {
connection = createSignalRConnection(getState);
startSignalRConnection();
connection.on("OnEvent", (res) => {
dispatch(
applicationApi.util.updateQueryData(
"getApplications",
undefined,
(prevApplications: TApplication[]): TApplication[] => [
...prevApplications,
res,
],
),
);
});
}
}
return next(action);
}; // store.ts
const createStore = (
options?: ConfigureStoreOptions["preloadedState"] | undefined,
) =>
configureStore({
reducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(mainApi.middleware, signalRMiddleware),
devTools: process.env.NODE_ENV === "development",
...options,
});
export const store = createStore(); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
The only comment i'd make is that updateQueryData uses Immer, so you can mutate the parameter: dispatch(
applicationApi.util.updateQueryData(
"getApplications",
undefined,
(prevApplications: TApplication[]) => { prevApplications.push(res) },
),
); Other than that, it's worth noting that the second parameter needs to match the argument used, and the cache entry needs to already be in state (i.e. you need something to be subscribed to it). |
Beta Was this translation helpful? Give feedback.
-
Hey, I've got another question. In the example we talked about earlier, the |
Beta Was this translation helpful? Give feedback.
The only comment i'd make is that updateQueryData uses Immer, so you can mutate the parameter:
Other than that, it's worth noting that the second parameter needs to match the argument used, and the cache entry needs to already be in state (i.e. you need something to be subscribed to it).