0

Not sure what I'm doing wrong. I know that I'm not able to access the proper this, but I thought using arrow function resolves that. my console.log(this) returns undefined.

handleSubmit(event) {
    event.preventDefault();
    const formData = {
        username: event.target.username.value,
        password: event.target.password.value
    }
    fetch('http://localhost:4000/user/login', {
        method: "POST",
        mode: "cors",
        body: JSON.stringify(formData),
        headers: {
            "Content-Type": "application/json"
        }
    })
    .then((res) => res.json())
    .then((res) => {
        if(res.token == undefined) {
            console.log(this)
            this.setState({ logFailureMsg: res.message })
        } else {
            localStorage.setItem('authorization', `Bearer ${res.token}`);
        }

    })
    .catch(err => console.error(err)) 
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Isaac
  • 59
  • 8
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Emile Bergeron Jan 16 '20 at 18:55
  • And specific to React: [`this` is undefined inside a component function](https://stackoverflow.com/q/33973648/1218980) – Emile Bergeron Jan 16 '20 at 18:56
  • no it doesn't. I did search the site before asking my question. I thought that using an arrow function will give access to the proper this. So, am I using arrow function wrong? – Isaac Jan 16 '20 at 18:56
  • 1
    You were debugging the wrong place, it's not inside the promise callbacks that `this` is undefined, it's in the whole `handleSubmit` function because you're probably not binding it nor it's an arrow function class member. – Emile Bergeron Jan 16 '20 at 19:00
  • 1
    Yes, this is correct, and actually clears up a lot of confusion for me. – Isaac Jan 16 '20 at 19:03
  • 1
    Context in JS is not a trivial concept and it gets in the way of every developer at some point. Whenever the context becomes undefined somewhere, go up the scope and make sure the context is what you're expecting it to be. It's a good first step to debug these kind of problems. ;) – Emile Bergeron Jan 16 '20 at 19:06

1 Answers1

2

This is not an arrow function. Change your function to look like this:

handleSubmit = event => {
    // your code...
}

Also, remember to call your function as this.handleSubmit, otherwise this will not be bound.

don_jon
  • 331
  • 3
  • 13
  • ah. I thought the .then((res) => {} was all I needed but the submit function needed to be an arrow function. This is very helpful. thanks. console.log(this) now returns the correct object. – Isaac Jan 16 '20 at 19:02