0

I have this state in my Parent component

const [formData, setFormData] = useState({
    firstName: "",
    middleInitial: "",
    lastName: "",
    imageFile: "",
    extension: "",
    mobileNumber: "",
    email: "",
    agreement1: false,
    agreement2: false,
    agreement3: false,
  });

and I pass it into the Child Component as a props but having an issue changing the value of agreement1 , agreement2 and agreement3 which is a Boolean

 setFormData({ ...formData, firstName: e.target.value })

This is the code in the Child Component to update the state into the Parent Component and it works perfectly fine. but when I try to update the Boolean I don't know how to access the previous boolean value before updating it.

I want to do something like this.

setBooleanValue((prevVal)=> !prevVal)

so every time I click on it . I toggle the value of the boolean

setFormData({...formData,agreement2: (prevVal) => !prevVal})

I try this but it doesn't work as expected

Mel Carlo Iguis
  • 126
  • 2
  • 9
  • 1
    You need to get reference from previous state and update the required field, `setFormData((prev) => { return { ...prev, agreement2: !prev.agreement2 }; });` Check this example, https://codesandbox.io/s/parent-child-component-forked-prvu88 – Maniraj Murugan Nov 04 '22 at 06:24
  • Thanks for the idea it's working fine now. But this is my approach but same concept to the one that you've said `setFormData({...formData,agreement2: !formData.agreement2})` I just get a reference value 1st in the `formData` props and then update it. – Mel Carlo Iguis Nov 04 '22 at 07:09

1 Answers1

1

you can try using the state update function as below:

setFormData((prev) => ({...prev,agreement2: !prev.agreement2}))

KcH
  • 3,302
  • 3
  • 21
  • 46
  • Thanks for the idea it's working fine now. But this is my approach but same concept to the one that you've said `setFormData({...formData,agreement2: !formData.agreement2})` I just get a reference value 1st in the `formData` props and then update it. – Mel Carlo Iguis Nov 04 '22 at 07:09
  • It works too, just in case to not get the stale value an updater function is being used – KcH Nov 04 '22 at 07:11