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();
}
Assuming
setValueis one of your hook, that you created like this:Then you can't use multiple
setValue, I mean, if you use:in one function, then
valuewill change only once, to the last value (here "titi").so you need to change
valuetype to an array / object and perform only 1setValuewith the modified object, like: