ReactJS componentDidMount and Fetch API
16,582
Solution 1
Since fetch
is async you'll need to do something like this:
componentDidMount() {
APIHelper.fetchFood('Dairy').then((data) => {
this.setState({dairyList: data});
});
},
Solution 2
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;
Author by
Nikkawat
Bare necessities: WiFi + Macbook Pro + Coffee Perfect Location!
Updated on June 27, 2022Comments
-
Nikkawat almost 2 years
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;