0

We have subjectChecks : [] as state .I fear that this method of changing state my go wrong .Is it ok to change state this way by pushing?

handleSubjectChange = (termID,subjectID) => event => {
          if(event.target.checked){
              this.state.subjectChecks.push({termID,subjectID});
          } else {
              this.state.subjectChecks.pop({termID,subjectID});
          }
          //this.setState({ [termID]: event.target.checked });
      };
SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • No you should not. And when accessing something in the previous state, use setState with a callback in which gets you access to the prevState – quirimmo Jan 08 '19 at 11:19
  • Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Quince Jan 08 '19 at 11:21

3 Answers3

1

Yes, this method of changing an array stored in state is wrong. You should make a copy of the original array, modify the copy and set it with setState:

let arr = this.state.subjectChecks.slice() //copy array
// modify arr as necessary
this.setState({subjectChecks: arr})
Sultan H.
  • 2,908
  • 2
  • 11
  • 23
kristaps
  • 1,705
  • 11
  • 15
  • this is a good approach to doing what u asked for, `slice()` to copy the original array, and then `setState()` to replace the old with the new one. – Sultan H. Jan 08 '19 at 11:47
  • Hey is this correct if i am trying to remove .else { let clonedarr=this.state.subjectChecks.pop(); this.setState({ subjectChecks:clonedarr }) – godfather_satyajeet Jan 08 '19 at 11:54
1

Use assign instead

this.setState({
    subjectChecks: [...this.state.subjectChecks, {termID,subjectID}]
});
Rafael Hovsepyan
  • 781
  • 8
  • 14
  • 1
    If accessing prev state, you should use the callback in setState which gives you access to the prevState – quirimmo Jan 08 '19 at 11:20
0

React (and redux) are built on the principle of state immutability. You should always use setState() to update your state, otherwise react will not detect state changes. See this answer.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

https://reactjs.org/docs/react-component.html#state

Community
  • 1
  • 1
Felix K.
  • 14,171
  • 9
  • 58
  • 72