2

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Rychu
  • 765
  • 1
  • 4
  • 20

2 Answers2

1

The endpoint's onQueryStarted property might be of better use for you here. You can run some additional logic when the query starts, or when it settles, i.e. when it completes.

Here's an example:

const api = createApi({
  baseQuery: ....,
  endpoints: (build) => ({
    getUser: build.query<...., ....>({
      query: ....,
      async onQueryStarted(_, { queryFulfilled }) {
        // `onStart` side-effect
        // anything you want to run when the query starts

        try {
          const { data } = await queryFulfilled
          // `onSuccess` side-effect
          // anything you want to run when the query succeeds
        } catch (err) {
          // `onError` side-effect
          // anything you want to run when the query fails
        }
      },
    }),
  }),
})
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thank you for your alternative, that would work indeed, but I don't feel my logic fits well into my API slice. I learned how to access an API endpoint matchers directly and that was what I needed (see my answer). – Rychu May 22 '23 at 09:35
  • @Rychu Fair enough, happy to help either way. Cheers and good luck! – Drew Reese May 22 '23 at 17:28
1

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);
};
Rychu
  • 765
  • 1
  • 4
  • 20