Search code examples
react-admin

ReferenceInput : using GET_ONE instead of GET_MANY like it was done in admin-on-rest


I am migrating from admin-on-rest to react-admin

Using the exact same Edit/SimpleForm/ReferenceInput combination, the behavior is different between admin-on-rest (seems to use GET_ONE) and react-admin (seems to use GET_MANY)

The problem is that my backend API does not support the GET_MANY

Does this mean that I have to modify my data provider to somehow transform a GET_MANY into multiple GET_ONE calls ?

If so, could you provide a basic example to do that.

Please note that this could be part of the documentation at https://marmelab.com/react-admin/Inputs.html#referenceinput since I suppose this is not uncommon


Solution

  • Waiting for a definitive answer to my question, here is what I did in my data provider based on https://marmelab.com/react-admin/DataProviders.html#example-request-processing :

    const convertRESTRequestToHTTP = (type, resource, params) => new Promise((resolve, reject) => {
        let url = '';
        const options = {};
        switch (type) {
            /* see other cases in the doc */
            case GET_MANY: {
                //our API does not support GET_MANY
                //=> we fallback to GET_ONE if there is a single id,
                //   otherwise we throw an error
                // also see convertHTTPResponseToREST to transform the JSON
                if (params.ids.length === 1) {
                  url = `${apiUrl}/${resource}/${params.ids[0]}`;
                  break;
                }
                throw new Error('the API does not support GET_MANY')
            }
        }
        resolve({ url, options });
    });
    
    const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { json } = response;
        switch (type) {
            /* see other cases in the doc */
            case GET_MANY:
                //see explanantion in convertRESTRequestToHTTP
                if (params.ids.length !== 1) {
                  throw new Error('the API does not support GET_MANY')
                }
                return { data: [json] };            
        }
    };