Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse subresource data for referenced inputs in React-admin?

In react-admin documentation the use of ReferenceArrayInput is for this kind of data structure:

{
  id: 1,
  groups: [1, 2, 3]
}

And then:

<ReferenceArrayInput source="groups" reference="groups" allowEmpty>
    <SelectArrayInput optionText="name"/>
</ReferenceArrayInput>

Using a custom json data provider, it will be make this request: https://example.com/api/groups/?ids=[1,2,3]

or if the API doesn't support WHERE IN, it will be do individual calls for each id:

https://example.com/api/groups/1
https://example.com/api/groups/2
https://example.com/api/groups/3

But if I have the following data structure:

{
  id: 1,
  name: "Pepito Perez",
  groups: [
    { id: 1, name: "HR"}, 
    { id: 2, name: "IT"},
    { id: 3, name: "FINANCE"}
  ]
}

I have the name field already, so I don't want make additional requests. When I go to the edit view react-admin performs almost 70 requests unnecessary.

How can I avoid that? there's a way to reuse the data?

Also is tricky use ReferenceArrayInput component with an array of objects, I have to add a nonsense format prop to make it works: format={v => (v ? v.map(i => (i.id ? i.id : i)) : [])}

Guess it's related to the first problem.

Thanks in advance!

like image 732
Genesis Guerrero Martinez Avatar asked Nov 01 '18 20:11

Genesis Guerrero Martinez


1 Answers

If the choices is not meant to be fetched, ReferenceInput is not what you want. You need only a SelectInput with programmatic setted choices. You can achieve that with FormDataConsumer:

        <FormDataConsumer>
            {({ formData, ...rest }) =>
                 <SelectArrayInput
                     source="selectedGroups"
                     optionText="name"
                     choices={formData.groups}
                     {...rest}
                 />
            }
        </FormDataConsumer>

Note a different source, probably setting as groups, equal to choices "source", after first selected group, would result in a re-render, letting choices values equal to the single selected group.

That's almost exactly the use case of FormDataConsumer in documentation:

https://marmelab.com/react-admin/Inputs.html#linking-two-inputs

like image 129
gstvg Avatar answered Nov 15 '22 08:11

gstvg