Search code examples
reactjsreact-adminreact-final-form

How to change/format the value in props input from react-final-form


In an edit form my API returns an array of ids [ 1, 2 ] to display advertisers in inputs, I used react-select for the for autocomplete but react-select needs : [{label: 'foo', value: 1}, {label: 'bar', value: 2}].

I get the labels in my component via a fetch and I would like to know how to change the values in react-final-form to have the right format.

Here is my EditForm :

const AgenciesInputs = ({
  getMany,
  record,
  sourceAdvertisers,
  sourceCreatedBy,
  sourceIsActive,
  sourceName,
  translate,
}) => {
  const [formatedAdvertisers, setFormatedAdvertisers] = useState([]);

  useEffect(() => {
    const { advertisers } = record;

    getMany(ADVERTISERS, advertisers, ({ payload: { data } }) =>
      setFormatedAdvertisers(data.map(({ id, name }) => ({ value: id, label: name }))),
    );
  }, []);

  console.log(formatedAdvertisers);

  return (
    <Root id="SLM_agenciesInputs">
      <TextInput autoFocus label="agencies_name" source={sourceName} validate={required()} />
      {!isNilOrEmpty(record) && (
        <TextInput
          disabled
          format={record => (record ? `${record.lastname} ${record.firstname}` : '')}
          label="agencies_createdBy"
          source={sourceCreatedBy}
        />
      )}
      <BooleanInput defaultValue label="agencies_isActive" source={sourceIsActive} />

      <Field
        component={CustomAutoCompleteInput}
        id="SLM_avertisersInput"
        minLength={1}
        name={sourceAdvertisers}
        placeholder={translate('agencies_advertisers')}
        url={sourceAdvertisers}
        validate={required()}
        isMulti
      />
    </Root>
  );
};


export default AgenciesInputs;

Solution

  • If you pass an options prop, it will be passed along to CustomAutoCompleteInput just like placeholder and isMulti are. Seems like you could just pass options={formatedAdvertisers}.