0

There is a some problem with this code, i think because `` setState is not working in this code.

this.setState({ 
  showTooltip: true, 
  toolTipsValue: message, 
  error: true 
})

Before click on a button

this.props.loginRes = {
  responseCode: 1, 
  result: {}
}

After Click on button

prevProps.loginRes = {
  responseCode: 1, 
  result: {}
}
this.props.loginRes = {
  responseCode: 1,
  result: { 
    data: {}, 
    statusCode: 1, 
    statusMessage: 'Invalid email/mobile' 
  }
}
componentDidUpdate(prevProps, prevState) {
  if (this.props.loginRes !== prevProps.loginRes) {
    const message = this.props.loginRes.result.statusMessage;
    this.setState({
      showTooltip: true,
      toolTipsValue: message,
      error: true
    })
  }
}

Error Message Error Message Link

Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52
  • 1
    Don't use `setState` inside a `componentDidUpdate`, it'll cause infinite rerender loop btw. https://stackoverflow.com/questions/30528348/setstate-inside-of-componentdidupdate – Loi Nguyen Huynh Dec 20 '19 at 09:39
  • 1
    @LoiNguyenHuynh you are right but i use condition so it's not go into infinite loop. also i attach error screen shot plz check it. – Ravi Patel Dec 20 '19 at 10:00
  • Could you show me the `Login.js` file, haven't seen anything wrong in your provided code yet. – Loi Nguyen Huynh Dec 20 '19 at 10:04

2 Answers2

1

The error this.setState is not a function is triggered because you didn't bind the onClick handler. As a result this points to the window object and not to the instance of your React class component. And the window object doesn't have setState() function as its property - that's what the error message says.

To fix this error either bind the onClick handler in the class constructor or rewrite the handler using an arrow function.

Using setState inside componentDidUpdate in the way you did should not cause endless loop.

winwiz1
  • 2,906
  • 11
  • 24
1

As an addition to winwiz1. (What he says is correct).

You are commparing two objects in the componentDidUpdate function. Comparing two objects with !== will not work. The answer why it isn`t working can be found here: Comparing two objects

The solution is lodash with isEqual, example can be found here: Depp comparison between 2 objects

Paul
  • 1,344
  • 4
  • 19
  • 37
  • He's comparing 2 objects by `!==`, which will always lead to `true` because they're always not the same object, then it's an infinite loop. A nice finding :)) – Loi Nguyen Huynh Dec 20 '19 at 14:14