2

I am trying to set state after axios calls. Inside then clause I have been trying to set state with this.setState({...}) but this is undefined here.

Why console.log(this) is printing 'undefined' in console?

  clickButton() {
    let data = {
      username : document.querySelector('#email').value,
      password : document.querySelector('#password').value
    };

    axios.post('http://127.0.0.1:8000/api/login_check', data, {
      headers: {
        'Content-Type' : 'application/json',
      }
    })
    .then(res => {
      console.log(this)
    })
  }
sensorario
  • 20,262
  • 30
  • 97
  • 159
  • 1
    Possible duplicate of [Why "this" is undefined inside a fat arrow function definition?](https://stackoverflow.com/questions/38589227/why-this-is-undefined-inside-a-fat-arrow-function-definition) – grooveplex May 19 '19 at 22:10
  • 1
    Due to this => ( Arrow Function ) – Farrukh Faizy May 19 '19 at 22:15

2 Answers2

1

The most obvious reason would be that since your clickButton function is not an arrow function you must have forgotten to bind your function in the constructor. Alternatively, switch clickButton to an arrow function and you should be fine.

KT-mongo
  • 2,044
  • 4
  • 18
  • 28
0

Try the following code to bind this to the click button function

clickButton = () => { .... }

Simon Thiel
  • 2,888
  • 6
  • 24
  • 46