@rxreact/context
Version:
Dependency-inject an RxJS signal graph into your React components
65 lines • 3.06 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 });
var React = require("react");
var core_1 = require("@rxreact/core");
function connect(context, viewModelFactory) {
return function connectWithComponent(Component) {
// The final component takes all the props of `component`,
// _except_ the ones passed in from the Signal Graph.
var Connected = function (props) {
// The Child component to render
var _a = React.useState({ Child: null }), Child = _a[0].Child, setChild = _a[1];
var _b = React.useState(null), localSubscriptions = _b[0], setLocalSubscriptions = _b[1];
var signalGraph = React.useContext(context);
// Wrap the child with `withViewModel`, but only do this once.
React.useEffect(function () {
var child = core_1.withViewModel(function (ownProps) {
var _a = viewModelFactory(signalGraph, ownProps), inputs = _a.inputs, outputs = _a.outputs, unsubscribe = _a.unsubscribe;
// Store the unsubscribes for cleanup.
setLocalSubscriptions(unsubscribe || null);
return { inputs: inputs, outputs: outputs };
})(Component);
// Wrap the child in an object, because `setChild` when passed a
// function (like a component) will actually call the function.
setChild({ Child: child });
}, [signalGraph]);
// On destroy, perform cleanup
React.useEffect(function () {
return function () {
if (localSubscriptions) {
localSubscriptions.map(function (subscription) { return subscription.unsubscribe(); });
}
};
}, [localSubscriptions]);
return Child ? React.createElement(Child, __assign({}, props)) : null;
};
return Connected;
};
}
exports.connect = connect;
/**
* Generate a SignalGraph context and provider to serve connected components.
* @param createSignalGraph - A function to generate the signal graph
*/
function createSignalGraphContext(createSignalGraph) {
var signalGraph = createSignalGraph();
var SignalGraphContext = React.createContext(signalGraph);
var SignalGraphProvider = function (_a) {
var children = _a.children;
return (React.createElement(SignalGraphContext.Provider, { value: signalGraph }, children));
};
return [SignalGraphContext, SignalGraphProvider];
}
exports.createSignalGraphContext = createSignalGraphContext;
//# sourceMappingURL=connect.js.map