React hook form setValue null not working

1.4k Views Asked by At

I am trying to use react hook form setValue to set every value that is equal to an empty string to null, but it doesnt work.

Any fixes?

const onSubmit = data => {
    for (const [key, value] of Object.entries(data)) {

      if (value === '') {
        setValue(key, null)
      }
    }
(Method here for sending data to api)
    reset();
  }
}

Edit:

I found this workaround for my issue:

const onSubmit = data => {
    let newData = data;

    Object.keys(newData).forEach((field) => {
      if (newData[field] === '') {
        newData[field] = null
      }
    })
    /Method for api here
    reset();
  }
1

There are 1 best solutions below

2
Paul-Marie On

Assuming setValue is one of your hook, that you created like this:

const [value, setValue] = useState();

Then you can't use multiple setValue, I mean, if you use:

setValue("toto");
setValue("tata");
setValue("titi");

in one function, then value will change only once, to the last value (here "titi").

so you need to change value type to an array / object and perform only 1 setValue with the modified object, like:

const array = Object.entries(data).map(([key, value]) => value === '' ? null : value);
setValue(array);