Search code examples
reactjsreact-reduxredux-toolkitrtk-query

React Toolkit Query - How to use transformResponse props with injectEndpoints()


I have a root API where I am injecting endpoints. But when I try to add a transform function it doesn't work. From the documentation of transformResponse I can see that the transform prop is attached to the query object.

Here is what I am trying

const departmentsApi = onboardApi.injectEndpoints({
    endpoints: builder => ({
        getDepartments: builder.query({
            query: params => ({
                url: `departments`,
                params,
                // Transform and normalize API response
            }),
            transformResponse: response => {
                 console.log('transform', response);
                 return response;
            },
            providesTags: result => {
                return result
                    ? [
                            ...result.items.map(({ id }) => ({ type: 'Department', id })),
                            { type: 'Department', id: 'LIST' },
                      ]
                    : [{ type: 'Department', id: 'LIST' }];
            },
        }),
    }),
    overrideExisting: false,
});

Any guidance will be helpful.

Resources

  1. Documentation for Injecting endpoints

Solution

  • You linked the docs of Redux-Query above, not RTK-Query. transform is not a thing. You probably want transformResponse:

    getDepartments: builder.query({
        query: params => ({
            url: `departments`,
            params,
            // Transform and normalize API response
            transform: response => {
                console.log(response);
                return response;
            },
        }),
        transformResponse: (response) => response.some.deeply.nested.collection,
        providesTags: result => {
            return result
                ? [
                        ...result.items.map(({ id }) => ({ type: 'Department', id })),
                        { type: 'Department', id: 'LIST' },
                  ]
                : [{ type: 'Department', id: 'LIST' }];
        },
    }),