Reputation: 27092
I'm new to React. I have gone through the tutorials, combed through a couple of example applications, and have spent some time writing some basic apps. But I'm still confused...
Something that is still bugging me after going through all of this is that I still don't really understand how (if?) React should be used to push data back to the server. There's obviously no data binding like Angular, and it's great to be able to use the Virtual DOM to update the page based on changing server-side data...But how can React be used to update data on the server? I'm not looking for a tutorial.
In jQuery (ajax), I can push data to the server without doing a page refresh. Can I do this using React? All of the examples are cute (hey, I can click this counter button and a number increments! hey, I can add a "comment" via this input and it's rendered on the page!), but how is this data then saved on the back-end? Is persistent data a thing without a page refresh? I'm failing to see what is gained by using React for this use case, over jQuery (for example).
I'm probably missing something simple, and a simple answer would be greatly appreciated.
Upvotes: 1
Views: 1871
Reputation: 8568
React is just the view layer and so you need to take care of other parts of application yourself.
I personally use the superagent which is also available on npm.
To have a better management of the API, I wrap it into a Service API class and then use it with promise returns like the example below
/* APIService.js */
var Q = require("q");
var Request = require("superagent");
//TODO: Define _urlPrefix, resource
module.exports = {
get: function(id, params) {
var deferred = Q.defer();
var url = _urlPrefix+"/"+resource+"/"+id;
Request
.get(url)
.set('X-Requested-With', 'XMLHttpRequest')
.query(params)
.end(function(res) {
if (res.status == 200) {
deferred.resolve(res.body);
} else {
deferred.reject(res.body);
}
})
;
return deferred.promise;
}
/* Other functions for POST, DELETE, PUT */
};
Upvotes: 1
Reputation: 71
In a previous project I worked on, we used jQuery to perform those POST requests to the server. We would catch the response and update the state of the object when it succeeded so the DOM would reflect the changes.
You have to take in mind that the mindset that React requires is different to Angular or Ember. By the way, I strongly suggest you watching this talk https://www.youtube.com/watch?v=-DX3vJiqxm4 from Pete Hunt where he goes through some differences between Angular/Ember/React, it changed the way I understood React.
Upvotes: 3