I have a value in my react state that looks like so:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
]
};
I have a new piece of data:
const newAppt = {"06-30-2018":[]}
How do I addon to my data in the state? I tried
this.setState({ ...this.state.appointmentsData, ...newAppt});
It seems to no be adding onto state though. I get back the same value in the render as before (appointmentData before spread). The newAppt never gets added to the state.
I am trying to get my states desired output to be:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
],
"06-30-2018": []
};
I have a value in my react state that looks like so:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
]
};
I have a new piece of data:
const newAppt = {"06-30-2018":[]}
How do I addon to my data in the state? I tried
this.setState({ ...this.state.appointmentsData, ...newAppt});
It seems to no be adding onto state though. I get back the same value in the render as before (appointmentData before spread). The newAppt never gets added to the state.
I am trying to get my states desired output to be:
appointmentsData = {
"05-01-2018": [
{
id: "1",
friendly: "9:00am - 10:00am",
openDateTime: "9:00am",
closeDateTime: "10:00am"
}
],
"06-30-2018": []
};
Share
Improve this question
asked Jun 30, 2018 at 22:02
allencodedallencoded
7,29517 gold badges75 silver badges133 bronze badges
1
- 1 What does your state look like exactly? Is object-rest-spread supported in your browser (or are you using a babel plugin for it)? – Damon Commented Jun 30, 2018 at 22:08
2 Answers
Reset to default 4Many ways to do it, really. Here's one:
this.setState(prevState => (
{appointmentsData: {...prevState.appointmentsData}, newAppt}
));
Though your approach should work too, if you just add the appointmentsData:
first. Like so:
this.setState({appointmentsData: {...this.state.appointmentsData, ...newAppt}});
This will spread all the previous values into a new object, plus the one you want to add.
I personally always use the functional way of setting the state when the new one depends on a previous state value, but your way is fine here too.
You should not use spread operator on newAppt
. Just go with:
this.setState({ ...this.state.appointmentsData, newAppt});
. It seems to me that the spread operator on newAppt
is not getting any data for the const
.