0

I have the below code where I am trying to update setState with few properties modified in array of objects

onClick(index) {
    let tmp = this.state.daysOfWeek;
    tmp[index].active = !tmp[index].active;
    if (tmp[index].active === true) {
      tmp[index].className = "selectedDay";
    } else {
      tmp[index].className = "remSelectedDay";
    }

    this.setState({ daysOfWeek: [...this.state.daysOfWeek, tmp]})
  }

Here tmp is modified array of objects. If I use spread operator then the arry of objects are concatinated wiht tmp.

How could I update the current state with array of objects ?

2
  • Loop through them using map and then return updated array. Commented Sep 20, 2019 at 10:07
  • How your state / days of week looks like? Commented Sep 20, 2019 at 10:08

2 Answers 2

1

A combination of map and the functional form of setState will allow you to correctly update the array without directly modifying the state:

onClick(index){
  this.setState(state => {
    return {
      daysOfWeek: state.daysOfWeek.map((day, i) => {
        if (i === index) {
          return {
            ...day,
            active: !day.active,
            className: day.active ? 'remSelectedDay' : 'selectedDay'
          }
        }
        return day;
      })
    }
  })
}
Sign up to request clarification or add additional context in comments.

Comments

0
onClick (index) {
    const { daysOfWeek } = this.state        // for example: [1, 2, 3, 4, 5], index = 1
    this.setState({
        daysOfWeek: [
            ...daysOfWeek.slice(0, index),               // [1]
            {
                ...daysOfWeek[index],                    // this is 2
                active: !daysOfWeek[index],
                className: daysOfWeek[index] ? 'selectedDay' : 'remSelectedDay'
            },
            ...daysOfWeek.slice(index + 1)               // [3, 4, 5]
        ]
    })
}

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.