UNPKG

infrastructure-components

Version:

Infrastructure-Components configure the infrastructure of your React-App as part of your React-Components.

61 lines 3.04 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importStar(require("react")); const exenv_1 = __importDefault(require("exenv")); const IsomorphicStateContext = react_1.default.createContext({}); const AttachIsomorphicState = (props) => { if (exenv_1.default.canUseDOM) { //at the client, get the value from the preloaded state return react_1.default.createElement(IsomorphicStateContext.Provider, { value: props.preloadedState }, props.children); } else { //at the server, we provide a callback function that sets the preloadedState return react_1.default.createElement(IsomorphicStateContext.Provider, { value: props.setServerValue }, props.children); } }; function withIsomorphicState(Component) { return function WrapperComponent(props) { return (react_1.default.createElement(IsomorphicStateContext.Consumer, null, (value) => { if (exenv_1.default.canUseDOM) { //console.log("value: ", value); //const [clientValue, clientSetter] = useState(value); // we ignore the clientProps...but we take the props from the preloadedState! return react_1.default.createElement(Component, Object.assign({}, props, { useIsomorphicState: (id, initialValue) => react_1.useState(value ? value[id] : undefined) })); } else { const useServerState = (id, intialValue) => { //console.log("initial server state: ", id, " -> ", intialValue); if (value) { value(id, intialValue, true); } ; const [serverValue, setValue] = react_1.useState(intialValue); const setServerValue = (newValue) => { // "value" is the function "setServerValue" from the Context if (value) { value(id, newValue); } // the normal hook setter setValue(newValue); }; return [serverValue, setServerValue]; }; // when on the server, we use the initial value as provided return react_1.default.createElement(Component, Object.assign({}, props, { useIsomorphicState: useServerState })); } })); }; } exports.withIsomorphicState = withIsomorphicState; exports.default = AttachIsomorphicState; //# sourceMappingURL=attach-isomorphic-state.js.map