Search code examples
typescriptreduxredux-toolkit

Dispatch action when createApi query is completed


I have the following piece of code:

export const documentApi = createApi({
  reducerPath: 'documentApi',
  baseQuery: fetchBaseQuery({
    baseUrl: setBaseUrl('/documents'),
    prepareHeaders: async (headers) => setHeaders(headers),
  }),
  endpoints: (builder) => ({
    getDocuments: builder.query<AssignNormalizedData, TGetDocumentsProps>({
      query: (params) => ({
        url: '',
        params,
      }),
    }),
  }),
});

I would like to dispatch an action with the response I get from the server for getDocuments.

Can I do it directly in the createApi scope?


Solution

  • This is what the endpoint's onQueryStarted function can be used for. Once a query is started you can access the query lifecycle api and await the query to be fulfilled and dispatch additional actions.

    Example:

    export const documentApi = createApi({
      reducerPath: 'documentApi',
      baseQuery: fetchBaseQuery({
        baseUrl: setBaseUrl('/documents'),
        prepareHeaders: async (headers) => setHeaders(headers),
      }),
      endpoints: (builder) => ({
        getDocuments: builder.query<AssignNormalizedData, TGetDocumentsProps>({
          query: (params) => ({
            url: '',
            params,
          }),
          onQueryStarted: async (arg, api) => {
            const { dispatch, queryFulfilled } = api;
    
            const { data } = await queryFulfilled;
            dispatch(someAdditionalAction(data));
          },
        }),
      }),
    });