javascript - setState in none React component in a seperate file -


doing xhr requests backend, want requests in separate file 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 setstate     // this.setstate({data: webapiutils.loadpost()});     // instead of     this.loadpost();   }   ,   // method working fine here, want use 1 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 working fine, want move xhr requests webapiutils.js file. proper way connect them , update state.

as felix advised check: how return response asynchronous call?

did callback function , works

../utils/webapiutils.js

var request = require('superagent'); var constants = require('../constants/constants');  var apiendpoints = constants.apiendpoints;  module.exports = {   // add callback   loadpost: function(callback) {     request.get(apiendpoints.user + '/' + 'ahmadajmi')       .set('accept', 'application/json')       .end(function(error, res) {         if (res) {           var json = json.parse(res.text);           callback(json);         }       });   } }; 

post.js

var react = require('react'); var webapiutils = require('../utils/webapiutils');  var post = react.createclass({   getinitialstate: function() {     return {data: ''}   }   ,   componentdidmount: function() {     // execute loadpost , setstate based on returned data     webapiutils.loadpost(function(result) {       this.setstate({data: result})     }.bind(this));   }   ,   render: function() {     return (       <div classname="post">       {this.state.data}       </div>     );   } }); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -