UNPKG

react-atom-toast

Version:
55 lines (52 loc) 1.66 kB
import '../chunk-5USKE2QT.js'; import { useMemo, useEffect, useRef } from 'react'; import { isFunction } from '../utils.js'; import { useMemoizedFn } from './use-memoized-fn.js'; import { usePrevious } from './use-previous.js'; import { useUpdate } from './use-update.js'; function useControlledState(option) { const { defaultValue, value, onChange, beforeValue, postValue, onInit } = option; const isControlled = Object.prototype.hasOwnProperty.call(option, "value") && typeof value !== "undefined"; const initialValue = useMemo(() => { let init = value; if (isControlled) { init = value; } else if (defaultValue !== void 0) { init = isFunction(defaultValue) ? defaultValue() : defaultValue; } return init; }, []); useEffect(() => { onInit == null ? void 0 : onInit(initialValue); }, [initialValue]); const stateRef = useRef(initialValue); if (isControlled) { stateRef.current = value; } const previousState = usePrevious(stateRef.current); if (postValue) { const post = postValue(stateRef.current, previousState); if (post) { stateRef.current = post; } } const update = useUpdate(); function triggerChange(newValue) { let r = isFunction(newValue) ? newValue(stateRef.current) : newValue; if (beforeValue) { const before = beforeValue(r, stateRef.current); if (before) { r = before; } } if (onChange) { onChange(r, stateRef.current); } if (!isControlled) { stateRef.current = r; update(); } } return [stateRef.current, useMemoizedFn(triggerChange), previousState]; } export { useControlledState };