I’m working on a React component where I need to update the state of an object that holds values for different days. However, when I update one field, the other fields get erased completely, leaving the object with only the field I changed.
Here’s the relevant part of my code:
const [dayValues, setDayValues] = useState({});
const handleInputChange = (day, field, value) => {
setDayValues(prevValues => ({
...prevValues, // for preserving all other days
[day]: {
...prevValues[day], // for preserving the other fields i dont change
[field]: value
}
}));
};
I have a state object dayValues that looks something like this:
{
"2023-10-01": { field1: 5, field2: 3, field3: 8 },
"2023-10-02": { field1: 2, field2: 4, field3: 2 }
}
When I call for example handleInputChange("2023-10-01", "field2", 4)
via a Numberinput with increment and decrement buttons like this:
<NumberInput onChange={(newField2Value) => handleInputChange(day, "field2", newField2Value)}/>
I expect the state to update to:
{
"2023-10-01": { field1: 5, field2: 4, field3: 8 },
"2023-10-02": { field1: 2, field2: 4, field3: 2 }
}
However, what actually happens is:
{
"2023-10-01": { field2: 4 },
"2023-10-02": { field1: 2, field2: 4, field3: 2 }
}
Why does my current implementation erase the other fields, and how can I fix it to preserve the existing fields while updating only the specific field?
Any help would be greatly appreciated!