Skip to content

Instantly share code, notes, and snippets.

@troygoode
Last active August 29, 2015 14:12
Show Gist options
  • Save troygoode/be64ac29ced3171f1f91 to your computer and use it in GitHub Desktop.
Save troygoode/be64ac29ced3171f1f91 to your computer and use it in GitHub Desktop.
Reflux & HTTP APIs
var ProductsApi = require('./api');
module.exports = Reflux.createActions({
'loadAll', // initiates the async load
'loadAllComplete', // when the load is complete
'loadAllError' // when the load has failed
});
module.exports.loadAll.preEmit = function (id) {
ProductsApi.loadAll()
.then(module.exports.loadComplete, module.exports.loadAllError);
};
var xhr = require('./xhr');
module.exports = {
loadAll: function () {
return xhr({
url: '/api/products'
});
}
};
var ProductActions = require('./actions'),
ProductsStore = require('./store');
module.exports = React.createClass({
componentWillMount: function () {
ProductsStore.listen(this.onProductsChange);
ProductActions.loadAll();
},
onProductsChange: function (state) {
this.setState(state);
}
});
var ProductActions = require('./actions');
module.exports = Reflux.createStore({
init: function () {
this.state = {
products: []
};
this.listenTo(ProductActions.loadAllComplete, this.onLoadAll);
},
getInitialState: function () {
return this.state;
},
onLoadAll: function (products) {
this.state.products = products;
this.trigger(this.state);
}
});
// this is just to wrap XMLHttpRequest in a promise
module.exports = function (options) {
var deferred = Q.defer(),
req = new XMLHttpRequest();
req.open(options.method || 'GET', options.url, true);
// Set request headers if provided.
Object.keys(options.headers || {}).forEach(function (key) {
req.setRequestHeader(key, options.headers[key]);
});
req.onreadystatechange = function(e) {
if(req.readyState !== 4) {
return;
}
if([200,304].indexOf(req.status) === -1) {
deferred.reject(new Error('Server responded with a status of ' + req.status));
} else {
deferred.resolve(e.target.result);
}
};
req.send(options.data || void 0);
return deferred.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment