0

I have a some question about how to access props or state in promise. I have username password input and one button.The actionClickSignIn function work when i click button.Then i click button it show error

"TypeError: Cannot read property 'props' of undefined"

i want to know how to access props or state in UserAuth. Thankyou

my constructor

this.actionClickSignIn = this.actionClickSignIn.bind(this);

my function , UserAuth is using axois

actionClickSignIn() {

  let {username,password} = this.state;
     this.props.setName("John")  // --- > It work !!!!
  UserAuth(username,password).then(function(res){
     this.props.setName(res.data.user.name)  //---> not work !!!!
     this.state.isLogin = true
  }).catch(function (error) {
     console.log(error);
  });
}

and reder function

<Button  type="button" onClick={this.actionClickSignIn}> Sign In</Button>
devnext
  • 872
  • 1
  • 10
  • 25
  • 2
    I think it's not duplicate, it's the opposite. OP should use arrow function syntax to pass context into the function passed as the first argument to "then". – rishat Jan 08 '18 at 14:31
  • @RishatMuhametshin, you are right. The target dupe post has the reverse problem. I missed that. Here is a relevant answer: https://stackoverflow.com/a/41772222/2030321 – Chris Jan 08 '18 at 14:42
  • 2
    In other words @devnext: replace `then(function(res){` with `then(res => {` or `then((res) => {`. – Chris Jan 08 '18 at 14:43
  • @Chris it’s not duplicate because state and props work in actionClickSignIn – devnext Jan 08 '18 at 14:56
  • or perhaps `}).catch` change to `}.bind(this)).catch` – Mark Schultheiss Jan 08 '18 at 15:04
  • Perhaps a more appropriate duplicate would be https://stackoverflow.com/q/30268550/125981 with this answer https://stackoverflow.com/a/30268723/125981 – Mark Schultheiss Jan 08 '18 at 15:05
  • Here is some background that may assist others as well http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/ – Mark Schultheiss Jan 08 '18 at 15:07
  • 1
    Note the net effect that @Chris suggests is to use a "fat arrow" function which captures the "this" of the containing scope. some doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this – Mark Schultheiss Jan 08 '18 at 15:16

0 Answers0