@ewb/reach-react
Version:
React Resource and Fetch stuff
67 lines (66 loc) • 3.13 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReachSocketProvider = exports.ReachSocketContext = void 0;
const React = require("react");
const react_1 = require("react");
const SocketConnection_1 = require("./SocketConnection");
const core_1 = require("../core");
const defaultState = {
connections: { current: [] },
addConnection: () => {
return new SocketConnection_1.ReachSocketConnection(null, '', '');
},
removeConnection: () => {
return new SocketConnection_1.ReachSocketConnection(null, '', '');
},
};
exports.ReachSocketContext = react_1.createContext(defaultState);
function ReachSocketProvider(_a) {
var { children, connections: defaultConnections = [], socketOpts = react_1.useMemo(() => ({}), []) } = _a, props = __rest(_a, ["children", "connections", "socketOpts"]);
const service = react_1.useContext(core_1.ReachContext);
const connections = react_1.useRef([]);
const url = props.url || service.url;
if (!url) {
throw new Error('ReachSocketProvider needs url. Provide in ReachProvider or Props');
}
const addConnection = react_1.useCallback((namespace = '', event = '', opts = socketOpts) => {
let connection = connections.current.find((x) => x.namespace === namespace);
if (!connection) {
connection = new SocketConnection_1.ReachSocketConnection(service, url, namespace, event, opts);
connections.current.push(connection);
}
return connection;
}, [service, connections, url, socketOpts]);
const removeConnection = react_1.useCallback((namespace = '') => {
const index = connections.current.findIndex((x) => x.namespace === namespace);
if (index > -1) {
connections.current[index].disconnect();
connections.current.splice(index, 1);
}
}, [connections, url]);
react_1.useEffect(() => {
for (const connection of defaultConnections) {
if (!connections.current.some((x) => x.namespace !== connection.namespace)) {
connections.current.push(new SocketConnection_1.ReachSocketConnection(service, url, connection.namespace, connection.event, socketOpts));
}
}
}, [service, url, defaultConnections, socketOpts]);
react_1.useEffect(() => {
return () => {
connections.current.map((x) => x.disconnect());
};
}, []);
return (React.createElement(exports.ReachSocketContext.Provider, { value: { connections, addConnection, removeConnection } }, children));
}
exports.ReachSocketProvider = ReachSocketProvider;