React-hook-form changes `undefined` to an empty string even on untouched fields

Viewed 1858

I have a form and some default values, like this:

const defaultValues = {text: 'text'};
reset(defaultValues);

In the form, there are two text inputs with names text and title.

The problem is, the value of title is changing into the empty string on every change of form state:

  useEffect(() => {
    const form = getValues();
    console.info(form, formState.touchedFields);
  }, [formState]);

Gives: {text: 'text', title: ''} and an empty object for touchedFields. This is quite critical since in the application there's a big difference between an undefined value and an empty string.

How can I make RHF not to change untouched values?

edit: take a look at this example: https://codesandbox.io/s/clever-jang-d2s4n?file=/src/App.js

1 Answers

So, as suggested here https://github.com/react-hook-form/react-hook-form/discussions/7826 the solution is to use a controller:

const {
    formState: { errors },
    setValue
  } = useFormContext<T>();
const { field } = useController<T>({ name });
...
<YourInputComponent
value={field.value}
onChange={(e) => {
setValue(name, e.target.value, { shouldDirty: true, shouldValidate: true });
}}
...

Not an ideal way, but it works

Related