react-server-redux
Version:
Redux support for React-Server
82 lines (64 loc) • 2.6 kB
JavaScript
;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
module.exports = function () {
function ReduxAdapter(store) {
_classCallCheck(this, ReduxAdapter);
this.stateWaitMap = {};
this.store = store;
}
//Search the state for the values we are waiting on
//State is considered ready when the waiting value is neither
//undefined or null
_createClass(ReduxAdapter, [{
key: 'checkStateStatus',
value: function checkStateStatus() {
var _this = this;
var state = this.store.getState();
Object.keys(this.stateWaitMap).forEach(function (stateKey) {
if (!_this.stateWaitMap[stateKey].resolved) {
var keys = stateKey.split('.');
var searchState = state;
var isSatisfied = true;
for (var y = 0; y < keys.length; y++) {
var key = keys[y];
if (!searchState.hasOwnProperty(key) || searchState[key] == null) {
//exit we arent ready yet :(
isSatisfied = false;
break;
}
searchState = searchState[key];
}
if (isSatisfied) {
_this.stateWaitMap[stateKey].resolved = true;
_this.stateWaitMap[stateKey].resolver(searchState);
}
}
});
}
//This implementation will watch for state changes and resolve once the state values
//are available
}, {
key: 'when',
value: function when(stateProps) {
var _this2 = this;
var promises = stateProps.map(function (stateProp) {
var promise = _this2.stateWaitMap[stateProp];
if (!promise) {
promise = new Promise(function (resolve) {
_this2.stateWaitMap[stateProp] = { resolver: resolve, resolved: false };
});
}
return promise;
});
//Check for state immediately once
this.checkStateStatus();
var unsub = this.store.subscribe(this.checkStateStatus.bind(this));
return Promise.all(promises).then(function () {
unsub();
return _this2.store.getState();
});
}
}]);
return ReduxAdapter;
}();