vue-hooks-plus
Version:
Vue hooks library
50 lines (49 loc) • 1.83 kB
JavaScript
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const vue = require("vue");
function useControlledState(value, defaultValue, onChange) {
var _a;
const isControlled = vue.computed(() => (value == null ? void 0 : value.value) !== void 0);
const initialValue = (_a = value == null ? void 0 : value.value) != null ? _a : defaultValue;
const internalState = vue.ref(initialValue);
const wasControlled = vue.ref(isControlled.value);
const currentValue = vue.computed(
() => isControlled.value ? value == null ? void 0 : value.value : internalState.value
);
vue.watchEffect(() => {
console.log("isControlled", isControlled.value);
});
vue.watch(isControlled, (newVal, oldVal) => {
if (newVal !== oldVal) {
console.warn(
`WARN: Component changed from ${wasControlled.value ? "controlled" : "uncontrolled"} to ${newVal ? "controlled" : "uncontrolled"}`
);
wasControlled.value = newVal;
}
});
function setValue(newValue, ...args) {
if (typeof newValue === "function") {
console.warn(
"Function callbacks are not supported."
);
const prev = currentValue.value;
const updatedValue = newValue(prev);
if (!isControlled.value) {
internalState.value = updatedValue;
}
if (!Object.is(prev, updatedValue)) {
onChange == null ? void 0 : onChange(updatedValue, ...args);
}
} else {
const shouldUpdate = !Object.is(currentValue.value, newValue);
if (!isControlled.value) {
internalState.value = newValue;
}
if (shouldUpdate) {
onChange == null ? void 0 : onChange(newValue, ...args);
}
}
}
return [currentValue, setValue];
}
exports.useControlledState = useControlledState;
;