@yamada-ui/use-controllable-state
Version:
Yamada UI useControllableState custom hook
56 lines (55 loc) • 2.16 kB
JavaScript
"use client"
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
useControllableState: () => useControllableState
});
module.exports = __toCommonJS(index_exports);
var import_utils = require("@yamada-ui/utils");
var import_react = require("react");
function useControllableState({
defaultValue: defaultValueProp,
value,
onChange: onChangeProp,
onUpdate: onUpdateProp = (prev, next) => prev !== next
}) {
const onChange = (0, import_utils.useCallbackRef)(onChangeProp);
const onUpdate = (0, import_utils.useCallbackRef)(onUpdateProp);
const [defaultValue, setDefaultValue] = (0, import_react.useState)(defaultValueProp);
const controlled = value !== void 0;
const resolvedValue = controlled ? value : defaultValue;
const setValue = (0, import_utils.useCallbackRef)(
(next) => {
const nextValue = (0, import_utils.runIfFunc)(next, resolvedValue);
if (!onUpdate(resolvedValue, nextValue)) return;
if (!controlled || (0, import_utils.isUndefined)(nextValue) || (0, import_utils.isNull)(nextValue))
setDefaultValue(nextValue);
onChange(nextValue);
},
[controlled, resolvedValue, onChange, onUpdate]
);
return [resolvedValue, setValue];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useControllableState
});
//# sourceMappingURL=index.js.map