react-admintextinput

Update <TextInput /> value in react-admin with an API response?


How can I change the <TextInput /> value in react admin to get an updated value which is from the API response?

Here is the code:

<TextInput source="..." label="..." />

I've tried to get used to setValue, and getValues from the useForm hook. But it doesn't work.


Solution

  • The react-admin@4.16.9 now using react-hook-form. So you can use the useFormContext to get the setValue

    But it only effects when you wrap your form with the FormProvider (in react-admin the provider will be something like <SimpleFormConfigurable>)

    
    const ControlledTextInput = ({ value, ...props }) => {
      const { setValue } = useFormContext();
    
      React.useEffect(() => {
        setValue(props.source, value);
      }, [value]);
    
      return <TextInput {...props} />;
    };
    
    
    // ==========
    
    <SimpleFormConfigurable>
       <ControlledTextInput
          source="title"
          validate={required("Required field")}
          value="this value was provide by API response"
       />
    </SimpleFormConfigurable>