redux-toolkitrtk-query

RTK Query correct way to map props with transformResponse


I'm working on linking up a scheduler component with data that I am receiving through an RTK Query api call. In order for the scheduler to work, I have to adjust the prop names to names the scheduler utilizes, before the state is available in the component (otherwise it does not load when I've tried in the React component). There is not a clear example of this being done in the RTK Query docs (https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#customizing-query-responses-with-transformresponse) , but it seems like it should be possible. When I've implemented it, the query gets fulfilled, but comes back as an empty object, or an array with a single empty object depending on how I've tried to structure it.

getUserScheduleVisits: builder.query({
            query: userId => `/visitapi/visits/users/${userId}`,
            providesTags: ['Visit', 'User'],
            transformResponse: (response) => {
                return {
                    data: [{
                        id: response._id,
                        startDate: response.visitStart,
                        endDate: response.visitEnd,
                        title: response?.client?.fullName
                    }]
                }
            },
        }),

When I've run the query without the transform response, the data comes through as expected, however remains unusable by the Scheduler component I'm trying to implement. I'm still learning the complexities to RTK Query so I'm sure its how I'm trying to use transformResponse, I'm just not sure how to approach it correctly.


Solution

  • This would end up as result.data.data if you do const result = useMyQuery().

    Did you maybe mean to do this?

    getUserScheduleVisits: builder.query({
                query: userId => `/visitapi/visits/users/${userId}`,
                providesTags: ['Visit', 'User'],
                transformResponse: (response) => {
                    return [{
                            id: response._id,
                            startDate: response.visitStart,
                            endDate: response.visitEnd,
                            title: response?.client?.fullName
                        }]
                },
            }),