UNPKG

@modern-kit/react

Version:
1 lines 2.92 kB
{"version":3,"file":"index.mjs","sources":["../../../src/hooks/useStepState/index.ts"],"sourcesContent":["import {\n isFunction,\n removeStorageItem,\n setStorageItem,\n} from '@modern-kit/utils';\nimport { UseStepProps, useStep } from '../useStep';\nimport { SetStateAction, useCallback, useState } from 'react';\n\ninterface StorageOptions {\n key: string;\n type: 'localStorage' | 'sessionStorage';\n}\n\ninterface UseStepWithInitialState<T> extends UseStepProps {\n initialState: T;\n storageOptions?: StorageOptions;\n}\n\ninterface UseStepWithoutInitialState extends UseStepProps {\n storageOptions?: StorageOptions;\n}\n\ntype UseStepStateProps<T> =\n | UseStepWithInitialState<T>\n | UseStepWithoutInitialState;\n\nexport function useStepState<T>({\n initialState,\n ...props\n}: UseStepWithInitialState<T>): ReturnType<typeof useStep> & {\n state: T;\n setState: (newState: SetStateAction<T>) => void;\n clearState: () => void;\n};\n\nexport function useStepState<T>(props: UseStepWithoutInitialState): ReturnType<\n typeof useStep\n> & {\n state: T | null;\n setState: (newState: SetStateAction<T | null>) => void;\n clearState: () => void;\n};\n\nexport function useStepState<T>(props: UseStepStateProps<T>) {\n const initialState = 'initialState' in props ? props.initialState : null;\n const { type, key } = props?.storageOptions ?? {};\n\n const [_state, _setState] = useState<T | null>(initialState);\n\n const setState = useCallback(\n (newState: SetStateAction<T | null>) => {\n _setState((prev) => {\n const newStateToUse = isFunction(newState) ? newState(prev) : newState;\n\n if (type && key) {\n setStorageItem(type, key, newStateToUse);\n }\n return newStateToUse;\n });\n },\n [type, key]\n );\n\n const clearState = useCallback(() => {\n if (type && key) {\n removeStorageItem(type, key);\n }\n _setState(null);\n }, [type, key]);\n\n return { state: _state, setState, clearState, ...useStep(props) };\n}\n"],"names":[],"mappings":";;;;AA2CO,SAAS,aAAgB,KAAA,EAA6B;AAC3D,EAAA,MAAM,YAAA,GAAe,cAAA,IAAkB,KAAA,GAAQ,KAAA,CAAM,YAAA,GAAe,IAAA;AACpE,EAAA,MAAM,EAAE,IAAA,EAAM,GAAA,EAAI,GAAI,KAAA,EAAO,kBAAkB,EAAC;AAEhD,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAI,SAAmB,YAAY,CAAA;AAE3D,EAAA,MAAM,QAAA,GAAW,WAAA;AAAA,IACf,CAAC,QAAA,KAAuC;AACtC,MAAA,SAAA,CAAU,CAAC,IAAA,KAAS;AAClB,QAAA,MAAM,gBAAgB,UAAA,CAAW,QAAQ,CAAA,GAAI,QAAA,CAAS,IAAI,CAAA,GAAI,QAAA;AAE9D,QAAA,IAAI,QAAQ,GAAA,EAAK;AACf,UAAA,cAAA,CAAe,IAAA,EAAM,KAAK,aAAa,CAAA;AAAA,QACzC;AACA,QAAA,OAAO,aAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IACA,CAAC,MAAM,GAAG;AAAA,GACZ;AAEA,EAAA,MAAM,UAAA,GAAa,YAAY,MAAM;AACnC,IAAA,IAAI,QAAQ,GAAA,EAAK;AACf,MAAA,iBAAA,CAAkB,MAAM,GAAG,CAAA;AAAA,IAC7B;AACA,IAAA,SAAA,CAAU,IAAI,CAAA;AAAA,EAChB,CAAA,EAAG,CAAC,IAAA,EAAM,GAAG,CAAC,CAAA;AAEd,EAAA,OAAO,EAAE,OAAO,MAAA,EAAQ,QAAA,EAAU,YAAY,GAAG,OAAA,CAAQ,KAAK,CAAA,EAAE;AAClE;;;;"}