0

I am trying to setState after an operation succeeds (which is succeeding) but it fail when trying to setState.

  .then(function () {                                       
        this.setState({ success: true, loading: false });                                           
    }).catch((error) => {
        console.log("Error on creating document: ", error); 
    })

..it catches the error which says :

"error = TypeError: Cannot read property 'setState' of undefined at eval"

it seems to me that it cannot find this context but why?

EDIT:

this didnt help How to access the correct `this` inside a callback?

showtime
  • 1
  • 1
  • 17
  • 48
  • The surrounding function must not be being called with the proper calling context – CertainPerformance Jan 17 '21 at 03:49
  • @CertainPerformance I dont understand what you mean, can you please elaborate a little more? – showtime Jan 17 '21 at 03:57
  • There isn't enough code in the question to say why, but your `this` is not referring to what you want it to be. – CertainPerformance Jan 17 '21 at 04:02
  • @CertainPerformance it should be referring to the state but how should I write the setState in another way that it actually refers to the state properly? Btw I am setting state inside asynchronous main function which has multiple nested async functions. Maybe when entering the nested functions it loses context?? – showtime Jan 17 '21 at 04:04
  • Found the solution: instead of doing this ` .then(function () => { ` do this instead ` .then((data) => { ` , I have no idea why ! – showtime Jan 17 '21 at 04:10
  • You are right on the last comment, @ssssss. The `this` in your example is in the context of the function and not the class. The use of a callback binds it to the component, so your fix works. To avoid this in the future (no pun intended), there are several options to make sure your `this` has the correct context. Check out here: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – ckesplin Jan 17 '21 at 04:35
  • Using a function() doesn't bind `this` to this callback. So use the arrow function `() =>` instead – Victor Jozwicki Jan 17 '21 at 12:44
  • @VictorJozwicki can you explain the difference tho?! – showtime Jan 18 '21 at 02:20
  • 1
    When you use `function()` you create a new `this`. It then references the newly created function (meaning you won't access what's around). Using arrow functions `() =>` won't create a new `this` and will instead use the one 'above' (read about scope if you wish to know more). If this promise is in a class, this will reference the class, therefore you can use `this.setState`. The other way you could do that is by using `.bind(this)` after the `function() {}.bind(this)`. It should work as well. – Victor Jozwicki Jan 18 '21 at 08:34

0 Answers0