react-admin

Is there a solution to transform values, after getOne?


Need to transform fetched object, (e.g {..., "key": {"keyName": "keyValue"}}) need to transform {..., [{"name": "keyName", "value": "keyValue"}]}

const { field }: any = useController({ name: 'headers', rules: { required: 'The field is required' } });

useEffect(() => {
    const newValue: { headerName: string; headerValue: any; }[] = []
        Object.keys(field.value).forEach(el => {
        newValue.push({ 'headerName': el, 'headerValue': field.value[el] });
    });
    // NOT UPDATING
    field.onChange(newValue)
}, []);

Solution

  • The withLifecycleCallbacks helper is made for this. This function allows you to adds logic to an existing dataProvider for particular resources, using pre- and post- event handlers like afterGetOne for instance.

    For instance:

    const baseDataProvider = myDataProvider('http://path.to.my.api/');
    export const dataProvider = withLifecycleCallbacks(baseDataProvider, [
        {
            resource: 'posts',
            afterGetOne: async (result, dataProvider) => {
                return transform(result); // transform the result and return it
            },
        },
    ]);
    

    Hope this helps :)