react-admin exclude “record” from the redux-form

杀马特。学长 韩版系。学妹 提交于 2019-12-12 16:22:22

问题


I have an issue when I send SimpleForm (edit) request with react-admin. The request includes more parameters than I have in the form's fields.

For example I have form:

<Edit {...props}>
    <SimpleForm>
        <TextInput source="title_new" />
        <TextInput source="age_new" />
    </SimpleForm>
</Edit>

It includes only 2 fields but when I click "save" the request includes more fields. I understood that those fields are coming from the GET_ONE request which fill the data from the DB.

GET_ONE:

{
title: 'title',
title_new: 'title-new',
age: 'age',
age_new: 'age-new',
}

The update request UPDATE:

{
title: 'title',
title_new: 'title-new',
age: 'age',
age_new: 'age-new',
}

I expect that the UPDATE will include only the forms fields (title_new and age_new) without the title and age fields that come from "record".

Those fields make me a lot of trouble on the API side and I want to avoid/exclude them from all the forms, basically I want to send only the form inputs with the SimpleForm inputs only.

Few solutions I have in mind: 1. "Altering the Form Values before Submitting" here 2. Manipulate the request in the restProvider

Both solutions are not good for me because I have many forms like that and the restProvider code will look bad. Also I don't want to "alter" any form I build.

PLEASE ADVICE.


回答1:


This is the way react-admin works. If you want the UPDATE dataProvider verb to post only the changes fields (and probably send a PATCH rather than a POST), you have to do it in the dataProvider.

I'm not sure that the provider will look bad after the change: all you have to do is to alter the UPDATE verb. By default, it looks like (for the simple rest provider):

            case UPDATE:
                url = `${apiUrl}/${resource}/${params.id}`;
                options.method = 'PUT';
                options.body = JSON.stringify(params.data);
                break;

You just need to update it like so:

            case UPDATE:
                url = `${apiUrl}/${resource}/${params.id}`;
                options.method = 'PUT';
-               options.body = JSON.stringify(params.data);
+               options.body = JSON.stringify(diff(params.data, param.previousData));
                break;

Where diff can be written as:

consy diff = (previous, current) => lodash.pickBy(current, (v, k) => previous[k] !== v);


来源:https://stackoverflow.com/questions/55010068/react-admin-exclude-record-from-the-redux-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!