UNPKG

r3bl-ts-utils

Version:

The `r3bl-ts-utils` package is a set of useful TypeScript functions and classes that can be used in Node.js and browser environments. They are inspired by Kotlin stdlib, and Rust to write code as expressions rather than statements, colorized text, powerfu

59 lines 2.71 kB
"use strict"; /* * Copyright (c) 2022 R3BL LLC. All rights reserved. * * 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 }); exports.useIsComponentMounted = exports.useStateSafely = void 0; const react_1 = require("react"); const kotlin_lang_utils_1 = require("../lang-utils/kotlin-lang-utils"); const expression_lang_utils_1 = require("../lang-utils/expression-lang-utils"); const react_core_utils_1 = require("./react-core-utils"); /** * Similar to [useState](https://reactjs.org/docs/hooks-reference.html#usestate) with some changes: * 1. Ensures that enclosing function component is mounted in order to update state. * 2. Returns an object instead of an array. * * @see https://reactjs.org/docs/hooks-reference.html#usestate * @param initialValue Make this the initial value for state. * @returns An object containing 2 items: the state, and a function that enables updating the * state if the component is not mounted. */ const useStateSafely = (initialValue) => { const isComponentMounted = (0, exports.useIsComponentMounted)(); const [state, setState] = (0, react_1.useState)(initialValue); // https://stackoverflow.com/a/41085908/2085356 const setStateOverride = (value) => (0, expression_lang_utils_1._callIfTruthy)(isComponentMounted.current, (_) => setState(value)); return new react_core_utils_1.StateHolder(state, setStateOverride); }; exports.useStateSafely = useStateSafely; /** * Runs an effect just once (onComponentDidMount) which sets the ref (that's returned) to true when * the component is mounted. And false when it isn't (hasn't been mounted yet, or has been * unmounted). */ const useIsComponentMounted = () => (0, kotlin_lang_utils_1._also)((0, react_1.useRef)(false), (ref) => { const updateRefOnMountAndUnmountEffectFn = () => { ref.current = true; // Clean up this hook. const cleanUpFn = () => { ref.current = false; }; return cleanUpFn; }; (0, react_1.useEffect)(updateRefOnMountAndUnmountEffectFn, []); }); exports.useIsComponentMounted = useIsComponentMounted; //# sourceMappingURL=use-state-safely.js.map