Search code examples
reactjsdictionarysetstate

React prevState parameter with map Function in setState


I am want to implement toggle functionality. (I have always used prevState to perform toggle operation) But in this case if I use prevState within map function. It is displaying error that "prevState is undefined". I am posting 2 code, first one is working without prevState...but I want to implement it using prevState as shown in example enter code here2 (but 2nd code is giving the above mentioned error)

Correct:

  this.setState({
            rawData: this.state.rawData.map(a => {
                if(a.id === id){
                    a.completed = !a.completed
                }
                return a
            })
        })

example 2:

this.setState((prevState)=>{
            rawData: this.state.rawData.map(a => {
                if(a.id === id){
                    a.completed = !prevState.a.completed
                }
                return a
            })
        })

Solution

  • I think the mapping is incorrect from the second example because you aren't mapping from the prevState. prevState.a is likely what is undefined. You need to also shallow copy the element being updated, otherwise a.completed = !a.completed is considered a state mutation.

    this.setState(prevState => ({
      rawData: prevState.rawData.map(a => {
        if (a.id === id) {
          return {
            ...a,
            completed: !a.completed,
          }
        }
        return a
      })
    }))