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": []
};
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)? Commented Jun 30, 2018 at 22:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.