0

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..
devjson
  • 113
  • 2
  • 16
  • Might be a problem from const { retainThisObj, ...restValues } = finalFormAPI.values I'm not sure what your are trying to do but you can try: ``` const retainThisObj = { retainThisObj, ...finalFormAPI.values } ``` – Andrei Ionita Feb 04 '21 at 14:32
  • Hi, can you expand your comment a little bit? basically I wanted to clear all fields values except for specific field. By the way I already figured it out and fixed it. – devjson Feb 04 '21 at 14:50

1 Answers1

1

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"}
      })
  }
devjson
  • 113
  • 2
  • 16