user9883888
user9883888

Reputation: 419

How to update state object key value?

I am declaring dateRangePicker field in component state like below

dateRangePicker: {
  selection: {
    startDate: new Date(),
    endDate: new Date(),
    key: 'selection',
  },
}

later start date and end date changes as below

let startDate = "2019-04-16";
let endDate = "2019-05-16";

But, I am not able to update these value in state after following code block

this.setState({
  dateRangePicker.selection.startDate : startDate,
  dateRangePicker.selection.endDate : endDate,
})

I want to update the start and end date accordingly

Upvotes: 1

Views: 937

Answers (3)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

It doesn't work the way you showed. It should be like this:

this.setState(ps=>({
 ...ps,
 dateRangePicker:{
   ...ps.dateRangePicker, // Copy old data
   selection: {
      ...ps.dateRangePicker.selection, // Same here
      startDate: startDate
      endDate: endDate

    },
 }
}))

We use functional form of setState, because you can see at one point we access data from previous state: ps.selection

Upvotes: 4

Ping Woo
Ping Woo

Reputation: 1773

The state is a immutable object, so you can not modified it, but create a new one, so using spread ... expression to create a new state.

Upvotes: 1

pope_maverick
pope_maverick

Reputation: 980

what your'e tryin to acheive is to change the state of a deep/nested object in setState..

const startDT = "new start date"
const endDT = "new end date"

this.setState(prevState => ({
 ...prevState,
 dateRangePicker: {
  ...prevState.dateRangePicker,
  selection: {
   ...prevState.dateRangePicker.selection,
    startDate: prevState.startDate = startDT,
    endDate: prevState.endDate = endDT,
  }
 }})
)

Or,

// copy without reference..
const dateRangePicker = { ...this.state.dateRangePicker }

dateRangePicker.selection = { 
 startDate: startDT,
 endDate: endDT,
}

this.setState({ dateRangePicker })

Upvotes: 1

Related Questions