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

  Kiến thức lập trình

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}
    />
  );
};

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT