Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ReferenceManyField Count?

Tags:

react-admin

How do you get to display a count of a "ReferenceManyField" component?

Here is the thing, I am listing organizations and I would like to get each of them their users counts.

Fetch organizations:

GET /organizations?filter={}&range=[0,24]&sort=["name","ASC"]

Fetch users for each organizations:

...
GET /users?filter={"uuid_organization":"1117b0a0-6ec7-40e3-9ee6-49d121c27111"}&range=[0,99]&sort=["email","ASC"]
...
    <List
        {...props}
        filters={<OrganizationFilter />}
        sort={{ field: 'name', order: 'ASC' }}
        perPage={25}
    >
        <Responsive
            xsmall={<MobileGrid />}
            medium={
                <Datagrid expand={<OrganizationShow />}>
                    <OrganizationLinkField />
                    <ReferenceManyField label="Users" reference="users" target="uuid_organization" sort={{ field: 'email', order: 'ASC' }}>
                        // PRINT: 102 users
                    </ReferenceManyField>
                    <EditButton />
                </Datagrid>
            }
        />
    </List>

I am not sure if I should do it this way, it seems inefficient and overkill. What you think?

Thanks in advance.

like image 319
fullmetalpacket Avatar asked Nov 07 '22 18:11

fullmetalpacket


1 Answers

The approach you chose is the way react-admin has implemented it to get joined data by foreign key and IMHO it is not that much of an overkill because on database level you still need to query the other table.

According to documentation, there is an extra response property for response format GET_MANY_REFERENCE called total: GET_MANY_REFERENCE { data: {Record[]}, total: {int} }

The ReferenceManyField field component uses this response format to retrieve data using the current record id as the foreign key (parent id) to the referenced resource.

Digging into react-admin code latest version 2.9.0 I see that ReferenceManyField passes props to it's children and it is up to you how you handle the data (e.g. List, DataGrid) and one of the props is total (count of records) which is by default passed to Pagination component.

You can create your own simple functional component to handle these props if you do not want to use anything else:

import React from 'react';

const UserTotal = props => <div>User count: {props.total}</div>;

export default UserTotal;

And the usage of your reference field:

<ReferenceManyField 
  label="Users" 
  reference="users" 
  target="uuid_organization" 
  sort={{ field: 'email', order: 'ASC' }}
>
  <UserTotal />
</ReferenceManyField>
like image 85
andris.vilde Avatar answered Dec 02 '22 22:12

andris.vilde