I have a piece of state which looks as so:
const [values, setValues] = useState({
firstName: '',
lastName: '',
dateOfBirth: {
month: '',
day: '',
year: ''
},
phoneNumber: '',
gender: '',
interests: [],
language: '',
medicareNumber: ''
})
I try to reassign the values of month day and year in the dateOfBirth object onChange, what is the syntax to do this and not overwrite any of the other keys in the object?
<input
value={values.dateOfBirth.month}
onChange={(e) => setValues({
...values,
dateOfBirth: { month: e.target.value }
})}
type='number'
placeholder='MM'
/>
<input
value={values.dateOfBirth.day}
onChange={(e) => setValues({
...values,
dateOfBirth: { day: e.target.value }
})}
type='number'
placeholder='DD'
/>
the code above is setting the value of dateOfBirth to only month or only day. But I need all the keys and values to remain the same and only change the value inside the respected key.
dateOfBirthinside itself before overwriting the key value pair you wantuseReducer. You have more control over the state.useStateis generally used for simple state variable like primitive values. en.reactjs.org/docs/hooks-reference.html#usereducer