UNPKG

@adpt/core

Version:
56 lines 2.24 kB
"use strict"; /* * Copyright 2019 Unbounded Systems, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("@adpt/utils"); const lodash_1 = require("lodash"); const error_1 = require("../error"); const jsx_1 = require("../jsx"); const hooks_1 = require("./hooks"); function useState(init) { const ctx = hooks_1.currentContext(); const stateInfo = ctx.options.hookInfo.stateInfo; const stateStore = ctx.options.stateStore; const elem = ctx.element; const count = stateInfo.get(ctx.element) || 0; stateInfo.set(ctx.element, count + 1); if (!jsx_1.isElementImpl(elem)) throw new error_1.InternalError(`Build context element is not ElementImpl`); const ns = elem.stateNamespace; let stateValue = stateStore.elementState(ns); if (stateValue === undefined) stateValue = {}; const key = "" + count; if (stateValue[key] === undefined) { stateValue[key] = lodash_1.isFunction(init) ? init() : init; stateStore.setElementState(ns, stateValue); } function setState(val) { const updater = async (prev) => { if (prev == null || !utils_1.isObject(prev)) throw new error_1.InternalError(`previous state was not an object`); if (lodash_1.isFunction(val)) val = val(prev[key]); return { [key]: await val }; }; if (!jsx_1.isElementImpl(elem)) throw new error_1.InternalError(`Build context element is not ElementImpl`); elem.setState(updater); } return [stateValue[count], setState]; } exports.useState = useState; //# sourceMappingURL=state.js.map