k102
k102

Reputation: 8079

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

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

Upvotes: 5

Views: 12079

Answers (2)

Shamah
Shamah

Reputation: 71

If anyone is still having this problem and doesn't want to use a Controller, i have a better solution by setting setValueAs inside the register method options:

<input
  {...register('familyNumber', {
    setValueAs: (value) => value || undefined,
  })}
/>

For more information you can read the documention here: https://react-hook-form.com/docs/useform/register

Upvotes: 6

k102
k102

Reputation: 8079

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

Upvotes: 1

Related Questions