UNPKG

@kwiz/fluentui

Version:
22 lines 1.31 kB
import { CommonLogger, isUndefined } from "@kwiz/common"; import { useEffect, useState } from "react"; const logger = new CommonLogger("useControlledStateTracker"); /** track an input control if it was changed from a managed to unmanaged (controlled / uncontrolled) state between renders. for example, if you pass a value on first render, but a defaultValue on a following render. */ export function useControlledStateTracker(props) { const [isUnControlled, setIsUnControlled] = useState(!isUndefined(props.defaultValue)); const __isUnControlled = !isUndefined(props.defaultValue); useEffect(() => { if (__isUnControlled !== isUnControlled) { logger.error(`${props.name} control was switched from controlled to uncontrolled mode. This is not supported.`); setIsUnControlled(__isUnControlled); if (!__isUnControlled) { setUncontrolledSelected(props.value); } } }, [__isUnControlled, isUnControlled]); const [uncontrolledSelected, setUncontrolledSelected] = useState(isUnControlled ? props.defaultValue : props.value); const valueToUse = isUnControlled ? uncontrolledSelected : props.value; return { valueToUse, setValue: setUncontrolledSelected }; } //# sourceMappingURL=use-controlled-state-tracker.js.map