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

3

5

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
Glossator answered 11/10, 2021 at 8:16 Comment(0)
T
9

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' }];
    },
}),
Tamarin answered 11/10, 2021 at 8:33 Comment(0)
D
2

Just a side note for anyone using queryFn instead of query: Using transformResponse with queryFn won't work.

This is logical if you think about it, because using queryFn already allows you to transform the response as you please.

Doley answered 4/6 at 12:9 Comment(0)
V
1

Additionally to eh answer from @phry in certain situations you might wana use queryFn

Lets say all your query received array of userIds, but your GET endpoint needs those usersIds as part of URL params in string. And in such case you will need to use queryFn and at the same time you cannot use transformResponse but still want to transform the result.

Then you can transform your data as following:

getDepartments: builder.query({
    async queryFn (arg, api, extraOptions, baseQuery) {
        if (arg.userIds.length === 0) {
          return { data: [] }
        }

        const response = await baseQuery({
          url: '/users',
          params: ({ userIds: arg.userIds.join(',') })
        })

        if ('data' in response) {
          return {
            data: response.data.map(item => ({
              ...item,
              // transform here
            }))
          }
        }

        return response as { data: GetApiResponse } | { error: { status: string, data: unknown } }// typescript type
      },
    providesTags: result => {
        ...
    },
}),
Vorfeld answered 23/8, 2023 at 6:11 Comment(2)
what could be the reason that you cannot use transformResponse?Mccormac
@MichaelFreidgeim typescript type works better like thisVorfeld

© 2022 - 2024 — McMap. All rights reserved.