Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
Michael Seltenreich Avatar asked Sep 21 '26 11:09

Michael Seltenreich


1 Answers

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));
      },
    }),
  }),
});
like image 118
Drew Reese Avatar answered Sep 23 '26 05:09

Drew Reese