@dabapps/roe
Version:
A collection of React components, styles, mixins, and atomic CSS classes to aid with the development of web applications.
57 lines • 2.03 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = void 0;
var React = require("react");
var Store = /** @class */ (function () {
function Store(initialState) {
var _this = this;
if (initialState === void 0) { initialState = {}; }
this.state = {};
this.listeners = [];
this.setState = function (state) {
_this.state = __assign(__assign({}, _this.state), state);
_this.listeners.forEach(function (listener) {
listener(__assign({}, _this.state));
});
};
this.getState = function () {
return __assign({}, _this.state);
};
this.subscribe = function (listener) {
if (_this.listeners.indexOf(listener) < 0) {
_this.listeners.push(listener);
}
return _this.createUnsubscriber(listener);
};
this.createUnsubscriber = function (listener) { return function () {
var index = _this.listeners.indexOf(listener);
if (index >= 0) {
_this.listeners.splice(index, 1);
}
}; };
this.useState = function () {
var _a = React.useState(_this.getState()), state = _a[0], setState = _a[1];
React.useEffect(function () {
var unsubscribe = _this.subscribe(setState);
return unsubscribe;
}, []);
return state;
};
this.state = initialState;
}
return Store;
}());
exports.Store = Store;
exports.default = new Store();
//# sourceMappingURL=store.js.map