0

I am working in a small application for a class I am taking and I have an issue when I am using the fetch API

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      map: "",
      markers: [],
      Data: []
    };
  }

  componentDidMount() {
    fetch(
      `https://api.foursquare.com/v2/venues/explore?near=ashkelon&v=20180729&client_id=MVLZGLPIAITJITM0OOFYER3C2ZRT5ERGGEWCC0T1YWV3HFZA&client_secret=1TBLTY0TSM1T320FEO3BJBGTMYVQPCMBOGO5GEBC0ZB1E5LK`
    )
      .then(function(response) {
        return response.json();
      })
      .then(
        function(data) {
          this.setState({ Data: data });
        }.bind(this)
      )
      .catch(function(e) {
        console.log("There is an issue with getting the information", e);
      });
  }
}

window.initMap = this.initMap;
loadJS("https://maps.googleapis.com/maps/api/js?key=AIzaSyDySeqpuOjQlckWJUMlbSW_w5CydOVTWJI&callback=initMap");

UPDATE : this will not provide with an error and the state is set, but what now happens is that my state is empty when i log the state in the initMap method.

At this point i see that the state is set for "that". But if its set for "that" how can i use "this" state in the rest of my application i need this information to create markers on the google maps API

thanks in advance.

4
  • use .bind(this); after your fetch call. Commented Jul 29, 2018 at 17:47
  • 1
    What's the actual issue? What have you tried? Because setting that = this will not change what this is elsewhere. Commented Jul 29, 2018 at 17:48
  • @Nick the issue is that I cannot setState with the data I'm trying to fetch Commented Jul 29, 2018 at 17:51
  • You should ask a new question now that you see new behavior. Be sure to include a minimal reproducible example when you do. Commented Jul 29, 2018 at 18:12

2 Answers 2

3

The problem is that this is undefined in your anonymous function. By assigning const that = this, you make the context from componentDidMount() available in all of the anonymous functions. Another solution is to bind() all functions with the correct context. For example

...
.then((function(data) {
    this.setState({Data: data.response.groups[0]})
    console.log(this.state.Data);
}).bind(this))
...

Now you can remove the declaration for that.

Sign up to request clarification or add additional context in comments.

6 Comments

I think what you were going to show is that in this way inside your block you can replace that with this
@quirimmo My bad. I missed that change in the copy-paste. Should be fix now. Thanks for pointing that out.
@Mike.G Did you also add the parentheses as shown in my code snippet?
@Code-Apprentice, yes ill udpate the code for you to see
@Mike.G Also update with the errors and fix the formatting
|
0

If you don't really care about IE11 support (and does not use Babel) please consider using arrow functions (it's syntax sugar for functions that have the same this as the this around them)

Note that string literals like you used, have similar compatibility table as arrow functions so you lose nothing and gain much cleaner code!

The code with arrow functions looks like this:

componentDidMount() {
   /* ... */

   fetch(`URL`)
      .then(response => response.json())
      .then(data => this.setState({Data: data.response.groups[0]}))
      .catch(e => console.log('There is an issue with getting the information' , e))

   /* ... */
}

1 Comment

I previously used ES6 functions, i saw a post that showed a solution with ES5 so i changed to ES5 functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.