useCustom transform response.
I have an array of vehicle models fetched from api. The sample model as follows
My data model looks like this:
How to map vehicle_type and fuel_types to vehicleType and fuelType of data model.
4 Replies
Hi @Anish. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Based on the information provided in the extracts, there isn't a direct example of mapping data from an API response to a different format. However, you can achieve this by using JavaScript's
map
function to iterate over the data and return a new array where the keys are renamed as per your requirements.
Here's an example of how you can do it:
In this code, mappedData
will be an array of objects where fuel_types
and vehicle_type
are renamed to fuelTypes
and vehicleType
respectively.
Please note that this is a general JavaScript solution and doesn't specifically pertain to the refine framework. For more specific use cases and features, you may want to refer to the refine documentation (https://refine.dev/docs).
----------------------
Note: you can ask me a follow up question by @ mentioning me again
:speech_balloon:
----------------------<@1132651711538941964> kapa.ai is still learning and improving, please let us how it did by reacting below
optimistic-goldOP•2y ago
This doesn't help. I've tried the above approach already. I am getting following error.
Property 'fuel_types' does not exist on type 'IVehicleModel'. Did you mean 'fuelTypes'?
wee-brown•2y ago
You could do something like this:
const { isLoading, refetch: getAuthUser } = useCustom<IUserResponse>({
queryOptions: {
enabled: true,
onSuccess: (data) => {
const serialized = getAuthUserRequest.serializer(data.data);
return setUserRequestSuccess(serialized);
},
},
url: getAuthUserRequest.url(),
method: getAuthUserRequest.method,
});
Alternatively you could add a serializer either within the meta or a general one:
serializeSnakeToCamel(data)
Thats how we do it in our application
the serializeSnakeToCamel would look like this (works also for nested objects)
export const serializeSnakeToCamel = (obj: any): any => {
if (obj === null || obj === undefined) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(serializeSnakeToCamel);
}
if (typeof obj === "object") {
return Object.keys(obj).reduce((result: { [key: string]: unknown }, key) => {
const camelKey = key.replace(/_\w/g, (m) => m[1].toUpperCase());
const camelValue = serializeSnakeToCamel(obj[key]);
result[camelKey] = camelValue;
return result;
}, {});
}
return obj;
};
So you have those two options:
1. Add it to "onSuccess" and save it in another state which you then type
2. Add it as a general serializer to the dataProvider OR pass it via the meta as a serializer that will be applied and then you can immediately type useCustom<Vehicle> which then has the correct property in camelCase format