Shamim Hasan
Shamim Hasan

Reputation: 319

Show edited value in aside in react-admin

I am using react-admin for admin interface. In edit form aside i want to show edited value (just to understand how to capture form changed values, later will show data from api for those changed values). My code as follows (Simplified)

const Aside = ({ record }) => {
  return (
    <div style={{ width: 200, margin: '1em' }}>
        <Typography variant="h6">Student details</Typography>
        <Typography variant="body2">
        {record && (
            <Typography variant="body2">
                {//Will Show current ArrayInput values here, Name/role of current students}
            </Typography>
        )}
        </Typography>
    </div>
)};

export const MyEdit = (props) => (
  <Edit aside={<Aside />} {...props}>
      <SimpleForm>
        <ArrayInput source="students">
                <SimpleFormIterator>
                  <TextInput source="name" /
                  <NumberInput source="role" />
                </SimpleFormIterator>
              </ArrayInput>
      </SimpleForm>
  </Edit>
);

How to update aside onchange of ArrayInput values?

Upvotes: 3

Views: 1372

Answers (1)

Fran&#231;ois Zaninotto
Fran&#231;ois Zaninotto

Reputation: 7335

React-admin uses react-final-form, which in turns uses a react Context to store the current form values.

that means that you can't access these values from outside the form (and I the aside is outside the form).

The solution is to store the current form values in a state shared by both SimpleForm and Aside (or even in the Redux store). To do so, use a FormSpy in the form, which will update the shared state when the value changes.

// in MyEdit.js
export const MyEdit = (props) => {
  const [formValues, setFormValues] = useState();
  return ( 
  <Edit aside={<Aside formValues={formValues} />} {...props}>
      <SimpleForm>
        <ArrayInput source="students">
                <SimpleFormIterator>
                  <TextInput source="name" /
                  <NumberInput source="role" />
                </SimpleFormIterator>
              </ArrayInput>
         <FormSpy
             subscription={{ valid: true }}
             onChange={props => {
                 setFormValues(props.values);
             }}
          />
      </SimpleForm>
  </Edit>
  );
};

Upvotes: 7

Related Questions