UNPKG

vue-hooks-plus

Version:
50 lines (49 loc) 1.69 kB
import { computed, ref, watchEffect, watch } from "vue"; function useControlledState(value, defaultValue, onChange) { var _a; const isControlled = computed(() => (value == null ? void 0 : value.value) !== void 0); const initialValue = (_a = value == null ? void 0 : value.value) != null ? _a : defaultValue; const internalState = ref(initialValue); const wasControlled = ref(isControlled.value); const currentValue = computed( () => isControlled.value ? value == null ? void 0 : value.value : internalState.value ); watchEffect(() => { console.log("isControlled", isControlled.value); }); 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]; } export { useControlledState };