I am trying to build a form with some nested data update. The code is as below:
On Change method
let student = {
name: null,
marks: { english: null },
};
const handleChange = (updatedValue) => {
student = {
...student,
...updatedValue,
marks: { ...updatedValue.marks },
};
console.log(student);
};
And my JSX:
<input
type="text"
className="form-control"
id="name"
placeholder="Name"
value={student.name ?? ""}
onChange={(event) =>
handleChange({
name: event.target.value,
})
}
/>
<input
type="text"
className="form-control"
id="english"
placeholder="English"
value={student.marks.english ?? ""}
onChange={(event) =>
handleChange({
marks: { english: event.target.value },
})
}
/>
The problem is that for "name" it works fine. But for "english", it behaves abnormally. E.g. when I enter "1" in English, it updates it to 1 in the console but on the UI, it immediately disappears from the input box. Also if I update it to 2, the value is replaced from one to 2.
The the expected value is 1
Can someone please help me identifying how to update the nested values correctly from the input box?
value={student.name ?? ""}|not??. ALso are you updating state or doing direct manipulation on object?