2

I am trying to update object's value using setState

In my code I am trying to update Date to 2019-06-22 and also update other values such as {dots: [vacation, massage, workout], selected: true}.

My Code:

this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      Date:'2019-06-22', :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))

This will give me an error. I think my code is okay but don't know what is wrong.

Any advise or comments would be really appreciated! Thanks in advance!

Thanks @bkm412 I have the solution:

const newDate = '2019-06-22'
   this.setState(({pressedDate}) => ({
     pressedDate: {
     ...pressedDate,
      [newDate] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))
1

2 Answers 2

3
this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      ['2019-06-22'] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))

If you want to use variable


const newDate = 'any date';
this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      [newDate] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help. But could you please check if the second code? it gives me an error saying that unexpected keyword 'const'
Oh.. sorry. I changed variable name
I think the code const newDate = '2019-06-22' has to be out side of setState. I moved it and it works great thanks. I'll edit my answer.
2

You want update Date to 2019-06-22 is okay, But I don't know what you to update into {dots: [vacation, massage, workout], selected: true}, He has no key.

You can try below code:

this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
     Date:'2019-06-22',
     dots: [vacation, massage, workout],
     selected: true,
  },
}));

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.