javascript - making restful api call from react js -
i doing poc isomorphic javascript application render html server side. poc working simple html, want make api call , json response , send render function. tried various ways not working. can 1 of please let me know missing.
i new react js , appreciated
loadcategoriesfromserver: function() { var self = this; // walking directions central park empire state building var http = require("http"); url = "api url here"; var request = http.get(url, function (response) { // data streamed in chunks server // have handle "data" event var buffer = "", data, route; response.on("data", function (chunk) { buffer += chunk; }); response.on("end", function (err) { data = json.parse(buffer); //console.log(data.d); //console.log(data.d.items); self.setstate({ categories: data.d.items }); }); }); }, // load server end getinitialstate: function() { return { categories: [] }; }, componentwillmount: function() { console.log("calling load categories") this.loadcategoriesfromserver(); }, render: function () { //console.log("data"); //console.log(this.state.categories); var postnodes = this.state.categories.map(function (cat) { console.log(cat); }); return ( <div id="table-area"> //i want paint data here.. </div> ) } });
fetching inside of component using componentwillmount
not right place, in case when need render server side. need somehow move out form component, , pass actual data props after fetched - example @jakesendar suggested in answer.
i have experience doing isomorphic app react, , main problem faced how wait until data loaded before first render
as @fakerainbrigand mentioned in comments, there not 1 way this, , depends requirements.
there few ways build isomorphic app, interesting perspective is: https://github.com/webpack/react-starter , http://fluxible.io/
but, elegant way this, figured out myself - organise asynchronous rendering react components, in particular using rxjs.
in general application structured following:
- views - react components without logic (just view)
models - observables current state (initial data loaded using superagent, combined other models and/or actions results). in simple case like:
rx.observable.defer(fetchdata).concat(updatessubject).sharereplay()
actions(or intents) - observers used collects user input, something, , dispatch action results subscribers models and/or other actions. in simple case like:
updatessubject = new rx.subject();
action = new rx.subject();
action.switchmap(asyncrequest).subscribe(updatessubject)
components - observables(stream of virtual dom elements) combined models, other components , actions (i have note this, explaining how , why create observable react elements rxjs), planning add partial components (tuple from: react component, observables, observers, , properties. partially filled using di)
router - component responsible handling location changes, in general main feature map location changes stream of virtual dom elements , meta information. in details, bit more complicated in case(url generation, active url highlighting, handling scrolls when navigating, has possibility of nested routes , multiple views)
all assembled using di container, in case similar angular2 di container, lot simplified specific needs.
components, models , actions created using di.
on server side application this:
var rootinjector = new injector(); // setup server specific providers rootinjector.provide(..., ...) app.get('/*', function(req,res){ var injector = rootinjector.createchild(); // setup request specific providers injector.provide(..., ...); injector.get(router) .first() .subscribe(function(routingresult){ res.render('app', { title: routingresult.title, content: react.rendertostring(routingresult.content) }); }); }
and similar on client side:
var rootinjector = new injector(); // setup server specific providers // omitted in case because default providers client side rootinjector.provide(..., ...) contentelement = document.getelementbyid('#content'); rootinjector.get(router) .subscribe(function(routingresult){ document.title = routingresult.title; react.render(routingresult.content, contentelement) });
in comparison flux, more declarative , more powerful way organise app. , in case of isomorphic app - me, looks better various hacks flux. of course there drawbacks... - more complicated.
likely later, opensource this, - not quite ready published.
upd1:
original answer bit outdated(later plan update it), , have progress in area.
links code mentioned above, opensourced:
- di container: di1
- container react componentns(connecting view observables , obsrvers): rx-react-container
- starter template, implementing isomorphic widgets, using rxjs , react, , libraries above: reactive widgets
about complete application(work still in progress, , documentation there not quite good, in general should clear):
- router built isomophic reactive applications router1 , react components use router1-react
- application template router , libraries mentioned above: router1-app-template
Comments
Post a Comment