1

I have component Inbox and having checkbox in it... But It works on third click... does not work on first and second click... setState works perfect but it does't re-render after setState

class Inbox extends PureComponent {
  constructor(props){
    this.state = {
      checked: [true]
    }
  }

  updateCheck(i, convId) {
    const state = this.state.checked
    state[i] = !state[i]
    this.setState(state)
  }

  render() {
    return (
       <input type="checkbox" checked={this.state.checked[i]} onClick={() => this.updateCheck(i, conv._id)}/>
    )
  }
}
1

1 Answer 1

1

You are not really updating the state correctly. setting state like

this.setState(state, () => {
  console.log(this.state, '787878787878778787')
})

does not update the checked state using state but adds keys with array indices to state like

{0: true, 1: false, conversationId: '', checked: [true, false]};

You are instead mutating the checked state yourself using

state[i] = !state[i]

To update the state correctly, you would write

updateCheck(i, convId) {
    const checked = [...this.state.checked]
    checked[i] = !checked[i]
    this.setState({ checked }, () => {
      console.log(this.state, '787878787878778787')
    })
 }

The problem in your approach arises because you mutate the original state directly, subsequent setState calls may replace the original change and hence you see that behaviour.

According to documentation

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

Working demo

Sign up to request clarification or add additional context in comments.

1 Comment

hey... It works... but what difference does this line make [...this.state.checked]

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.