react-hook-form controller with auto update value on mount

clock icon

asked 3 months ago Asked

message

0 Answers

eye

19 Views

I need to make it so that the value is set automatically when mounted. From outside the component I can't set it, because I have scripts when data retrieval requests happen in the component

The problem is that if I call onChange inside useEffect the component in render is not rendered because field.value is not changed, although field.onChange is triggered.

Is it possible to somehow set the value from inside the component in render method or it can't be done that way at all?

type TProps = {
  value: string;
  onChange?: (value: string) => void;
};
const TestInput = ({ onChange, value }: TProps) => {
  useEffect(() => {
    onChange?.('AutoSet');
  }, []);
  return <div>{value || 'empty'}</div>;
};

type Props = {
  name: string;
  control: Control<FieldValues>;
};
const TestInputController = ({ name, control }: Props) => {
  return (
    <Controller
      control={control}
      render={({ field, fieldState, formState }) => {
        return (
          <TestInput
            value={field.value}
            onChange={(value) => {
              field.onChange(value);
            }}
          />
        );
      }}
      name={name}
    />
  );
};

 

0 Answers

Write your answer here

Top Questions