Nikkawat
Nikkawat

Reputation: 79

ReactJS componentDidMount and Fetch API

Just started using ReactJS and JS, is there a way to return the JSON obtained from APIHelper.js to setState dairyList in App.jsx?

I think I'm not understanding something fundamental about React or JS or both. The dairyList state is never defined in Facebook React Dev Tools.

// App.jsx
export default React.createClass({
  getInitialState: function() {
    return {
      diaryList: []
    };
  },
  componentDidMount() {
    this.setState({
      dairyList: APIHelper.fetchFood('Dairy'), // want this to have the JSON
    })
  },
  render: function() {
   ... 
  }


// APIHelper.js
var helpers = {
  fetchFood: function(category) {
    var url = 'http://api.awesomefoodstore.com/category/' + category

    fetch(url)
    .then(function(response) {
      return response.json()
    })
    .then(function(json) {
      console.log(category, json)
      return json
    })
    .catch(function(error) {
      console.log('error', error)
    })
  }
}

module.exports = helpers;

Upvotes: 5

Views: 19709

Answers (2)

Nikkawat
Nikkawat

Reputation: 79

It works! Made changes according to Jack's answer, added .bind(this) in componentDidMount() and changed fetch(url) to return fetch (url)

Thanks! I now see State > dairyList: Array[1041] with all the elements I need

// App.jsx
export default React.createClass({
  getInitialState: function() {
    return {
      diaryList: []
    };
  },
  componentDidMount() {
    APIHelper.fetchFood('Dairy').then((data) => {
      this.setState({dairyList: data});
    }.bind(this));
  },
  render: function() {
   ... 
  }


// APIHelper.js
var helpers = {
  fetchFood: function(category) {
    var url = 'http://api.awesomefoodstore.com/category/' + category

    return fetch(url)
    .then(function(response) {
      return response.json()
    })
    .then(function(json) {
      console.log(category, json)
      return json
    })
    .catch(function(error) {
      console.log('error', error)
    })
  }
}

module.exports = helpers;

Upvotes: 1

Jack
Jack

Reputation: 21163

Since fetch is async you'll need to do something like this:

componentDidMount() {
  APIHelper.fetchFood('Dairy').then((data) => {
    this.setState({dairyList: data});
  });
},

Upvotes: 8

Related Questions