'Aggregate two columns into one

We have in a List view a Datagrid which among other fields uses two ReferenceField columns.

<List {...props}>
    <Datagrid>
        <ReferenceField reference="client-active" source="id" link="show" label="Client (active)">
            <ClientProfileSummary  />
        </ReferenceField>
        <ReferenceField reference="client-passive" source="id" link="show" label="Client (passive)">
            <ClientProfileSummary  />
        </ReferenceField>
    </Datagrid>
</List>

Now, each record either has one or the other reference, but never both. Is there a way so that we only have one column and take whichever value is present? Everything else is equal, it's just another resource.



Solution 1:[1]

If I understand properly, you have to create a component as below :

import React, { useCallback } from 'react'
import { useReference, LinearProgress, ResourceContextProvider, ReferenceField } from 'react-admin'
import { get } from lodash
import ErrorIcon from '@material-ui/icons/Error'

const TwoFieldsToOneField = (props) => {
  const { label, children, source, activeClientReference, passiveClientReference, ...rest } = props
  const id = get(record, source)
  
  const activeClientState = useReference(activeClientReference, id);
  const passiveClientState = useReference(passiveClientReference, id);
  
  const error = activeClientState.error ? activeClientState.error : passiveClientState.error
  if (error) {
    return (
      <ErrorIcon
        aria-errormessage={error.message ? error.message : error}
        role="presentation"
        color="error"
        fontSize="small"
      />
    );
  }

  if (!activeClientState.loaded || !passiveClientState.loaded) {
    return <LinearProgress />
  }

  if (!activeClientState.data && !passiveClientState.data) {
    return null
  }

  let reference = ""
  if (activeClientRecord) {
    reference = "client-active"
  } else if (passiveClientRecord) {
    reference = "client-passive"
  }
  
  return (
    <ReferenceField reference={reference} source="id" link="show" label={label}>
      {children}
    </ReferenceField>
  )
}

...

<List {...props}>
    <Datagrid>
        <TwoFieldsToOneField activeClientReference="client-active" activeClientReference="client-passive" source="id" link="show" label="Active/Passive">
            <ClientProfileSummary  />
        </TwoFieldsToOneField >
    </Datagrid>
</List>

However it may not be the most optimal and send 2x one of the API calls.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricola3D