docs aren't enough clear for me https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#customizing-query-responses-with-transformresponse
I've got an API call with createApi
getDashboard: builder.query<DashboardResponse, { id: string }>({
query: params => ({
url: `/v2/companies/${params.id}/dashboard`,
method: 'GET',
params: {
id: params.id
}
}),
})
and response looks like this:
{
"yearly_balance": {
"year": 2022,
"profit": {
"amount": 441394.4,
"currency": "PLN"
},
"loss": {
"amount": 298008.75,
"currency": "PLN"
},
"balance": {
"amount": 143385.65,
"currency": "PLN"
}
},
"current_social_security": {
"date": "2022-05-01",
"due_date": "2022-06-20",
"due_dates_number": 1,
"amount": [
{
"amount": 3066.0,
"currency": "PLN"
}
]
},
"current_taxes": {
"date": "2022-05-01",
"first_due_date": "2022-06-30",
"first_tax_kind": "quarterly",
"due_dates_number": 0,
"sum": [
{
"amount": 0.0,
"currency": "PLN"
}
]
}
}
I need to transform the response from this above to camelCase. I know that I need to add a function transformResponse but honestly I don't know how it works there. I'm a begginer in redux things.
I was able to find a solution on [stackoverflow](https://stackoverflow.com/questions/71503552/rtk-query-transform-all-query-responses-at-once) where I got the understanding to fabricate my own solution .
I created a custom baseQueryWithChange function to (globally) define a transformResponse for all queries and I wrap baseQuery with the custom baseQuery **function to transform API response**
export const changeResponse = async (list) => { const dataArray = list.data console.log(dataArray) // 10 elements const finalArray = await dataArray.filter((each) => each.length !== 1) // 6 elements const normalizeData = (data) => { return data.flatMap((d) => { return { ...d[0], ...d[1] }; }); }; const latestList = normalizeData(finalArray); console.log(normalizeData(finalArray)); // 6 elements return latestList }**baseQuery**
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; // import function to transform API response import { changeResponse } from "../../constants/changeResponse"; const baseQuery = fetchBaseQuery({ baseUrl: "http://localhost:3500" }) const baseQueryWithChange = async (args, api, extraOptions) => { let result = await baseQuery(args, api, extraOptions); if (result.data) { result.data = changeResponse(result.data) console.log(result.data) } return result } export const apiSlice = createApi({ baseQuery: baseQueryWithChange, endpoints: builder => ({}) })