UNPKG

@clayui/shared

Version:

ClayShared component

45 lines (43 loc) 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useControlledState = useControlledState; var _react = require("react"); var _warning = _interopRequireDefault(require("warning")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * SPDX-FileCopyrightText: © 2021 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: BSD-3-Clause */ function useControlledState(_ref) { let { defaultName, defaultValue, handleName, name, onChange, value } = _ref; const [stateValue, setStateValue] = (0, _react.useState)(defaultValue === undefined ? value : defaultValue); const ref = (0, _react.useRef)(value !== undefined); const wasControlled = ref.current; const isControlled = value !== undefined; if (wasControlled !== isControlled) { console.warn(`WARN: A component changed from ${wasControlled ? 'controlled' : 'uncontrolled'} to ${isControlled ? 'controlled' : 'uncontrolled'}. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled '${name}' prop for the lifetime of the component.`); } ref.current = isControlled; "production" !== "production" ? (0, _warning.default)(!(typeof onChange === 'undefined' && typeof value !== 'undefined'), `You provided a '${name}' prop for a component without a handler '${handleName}'. This will render the component with an internal state, if the component is to be uncontrolled, use '${defaultName}'. Otherwise, set the '${handleName}' handler.`) : void 0; const setValue = (0, _react.useCallback)(value => { if (!isControlled) { setStateValue(value); } if (onChange) { onChange(value); } }, [isControlled, onChange]); if (!isControlled) { value = stateValue; } return [value, setValue, !isControlled]; }