Trying to clear my react-final-form fields but I got empty object values instead

1k Views Asked by At

Here's my scenario, I'm clearing all fields values except for "retainThisObj" the rest clear values on initial page load.

My issue is I got empty { } in short my "retainThisObj" has been deleted as well. I expected this { retainThisObj }

Here's my code

import { useForm } from 'react-final-form'

  const finalFormAPI = useForm()
  const { retainThisObj, ...restValues } = finalFormAPI.values

 // func 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])

According to @Erik R. / the author

You can just call form.change('fieldName', undefined) at any time that you'd like to clear the value.

What I'm doing is adding a little bit logic to make code efficient. because If you have lots of fields values you end up like this.

form.change('fieldName1', undefined)
form.change('fieldName2', undefined)
form.change('fieldName3', undefined)
form.change('fieldName4', undefined)
and so on..
1

There are 1 best solutions below

0
On

I think I figured out why, I'm returning obj[value] instead just value

updated code

// func to reset field values
  const reset = (obj) => {
    Object.keys(obj).length &&
      Object.keys(obj).forEach((value) => {
        finalFormAPI.change(value, undefined) 
       // I need the value itself not obj[value] or { name: "value"}
      })
  }