I want to fire some side-effects after one of my RTKQ queries completes. I decided the best way would be to do it inside a middleware but I'm not sure what is the correct way to get catch this action.
After some debugging, I end up with something like below but it looks a bit hackish to me.
const recreateTransferOnAppStartMiddleware: Middleware<unknown, RootState> =
storeApi => next => action => {
const isFulfilledAction = action.type === `api/executeQuery/fulfilled`;
const isGetUserAction = action.meta
&& action.meta.arg
&& action.meta.arg.endpointName === `getUser`;
if (isFulfilledAction && isGetUserAction)
recreateTransfers(storeApi);
return next(action);
};
My biggest problem with this code is that it is string based when checking for endpointName
and action.type
.
After some digging, I found it is possible to access an endpoint matcher directly:
const recreateTransferOnAppStartMiddleware: Middleware<unknown, RootState> = storeApi => next => action => {
const isGetUserFulfilled = userApiSlice.endpoints.getUser.matchFulfilled(action);
if (isGetUserFulfilled)
recreateTransfers(storeApi);
return next(action);
};