UNPKG

vue-hooks-plus

Version:
47 lines (46 loc) 1.58 kB
import { computed, ref, watch } from "vue"; function useControlledState(value, defaultValue, onChange) { var _a; const isControlled = computed(() => value.value !== void 0); const initialValue = (_a = value.value) != null ? _a : defaultValue; const internalState = ref(initialValue); const wasControlled = ref(isControlled.value); const currentValue = computed( () => isControlled.value ? value.value : internalState.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. See: https://github.com/adobe/react-spectrum/issues/2320" ); 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 };