Currently, I am facing a situation where I need to clear all field values except for "retainThisObj"
upon the initial page load.
The problem I encountered is that my { } ended up empty, meaning that my "retainThisObj"
was also deleted. What I expected was to preserve this { retainThisObj }
Below is the code snippet:
import { useForm } from 'react-final-form'
const finalFormAPI = useForm()
const { retainThisObj, ...restValues } = finalFormAPI.values
// Function to reset field values
const reset = (obj) => {
Object.keys(obj).length &&
Object.keys(obj).forEach((value) => {
finalFormAPI.change(obj[value], undefined)
})
}
useEffect(() => {
reset(restValues)
}, [restValues])
As suggested by @Erik R. / the author
You can simply call form.change('fieldName', undefined) whenever you want to clear the value.
My approach involves adding some logic to enhance the code efficiency, especially when dealing with a large number of field values.
form.change('fieldName1', undefined)
form.change('fieldName2', undefined)
form.change('fieldName3', undefined)
form.change('fieldName4', undefined)
and so on..