Doing some xhr requests to the backend, I want all my requests to be in a separate file that is WebAPIUtils.js
../utils/WebAPIUtils.js
var request = require('superagent');
var constants = require('../constants/constants');
var APIEndPoints = constants.APIEndPoints;
module.exports = {
loadPost: function() {
request.get(APIEndPoints.USER + '/' + 'ahmadajmi')
.set('Accept', 'application/json')
.end(function(error, res) {
if (res) {
var json = JSON.parse(res.text);
return json;
}
});
}
};
post.js
var React = require('react');
var WebAPIUtils = require('../utils/WebAPIUtils');
// other requires
var Post = React.createClass({
getInitialState: function() {
return {data: ''}
}
,
componentDidMount: function() {
// Want to setState like this
// this.setState({data: WebAPIUtils.loadPost()});
// instead of this
this.loadPost();
}
,
// this method is working fine here, but I want to use the one in `WebAPIUtils.js` file
loadPost: function() {
request.get(APIEndPoints.USER + '/' + 'ahmadajmi')
.set('Accept', 'application/json')
.end(function(error, res) {
if (res) {
var json = JSON.parse(res.text);
this.setState({data: json})
}
}.bind(this));
},
render: function() {
return (
<div className="post">
{this.state.data}
</div>
);
}
});
The above code is working fine, but I want to move all my xhr requests to WebAPIUtils.js
file. So what is the proper way to connect them and update the state.