0

enter image description here

In the picture, I want to get lat and lng to setState but somehow get the error "Cannot read property 'setState' of undefined". I'm newbie so I don't know why. I hope everyone can fix and explain more

Charlie
  • 22,886
  • 11
  • 59
  • 90
Jame
  • 27
  • 4
  • 4
    please don't post pictures of code; paste it into the question instead. – Christian Fritz Apr 12 '21 at 15:55
  • 3
    short answer - use an arrow function inside the `.then` – Robin Zigmond Apr 12 '21 at 15:55
  • [There's probably a better duplicate that's more specific to this question, but this was the first I found, and goes into great detail about the relevant differences between arrow function and `function` declarations] Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – Robin Zigmond Apr 12 '21 at 15:58

2 Answers2

2

You are trying to access this.setState inside an anonymous function. It seems that the function is not bound to a context which has the setState method. Using an arrow function would solve this problem.

.then(result => {

   ....

   this.setState ...

)

The this keyword inside a function is bound to the calling context. But arrow functions don't have its own this context and if used, it would refer to the parent context;

Helpful links:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Charlie
  • 22,886
  • 11
  • 59
  • 90
1

Move the function inside of .then() and name it.

function thenFn(result) { .... }

Now you can bind ‘this’ to whatever you need it too with:

.then(thenFn.bind(this))

EDIT

As specified by commenters, you can fix this much more elegantly with an arrow function. All you need to do for that is to change:

.then(function (result) { .... })

To

.then((result) => { .... })

Essentially just remove ‘function’ and add an arrow between the parameters and brackets.

Luke Weaver
  • 271
  • 1
  • 9