0

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": []
};
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • 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 Jun 30 '18 at 22:08

2 Answers2

4

Many 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.

Chris
  • 57,622
  • 19
  • 111
  • 137
2

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.

Arslan Tariq
  • 2,478
  • 2
  • 22
  • 45