diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-10-26 19:07:31 +0200 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-11 18:15:27 +0100 |
| commit | 795b92cc1a168c48c7710ca6e0e1ef5974013d95 (patch) | |
| tree | 8f57204b0ffe7c8acb3203a24292f375377b6369 /src/components/organisms | |
| parent | 9aeb82269d7c74c4566b7ca254782a4dfbd69a6e (diff) | |
refactor(hooks): rewrite useLocalStorage hook
* return a tuple instead of an object
* add a validator function as parameter (if the stored value
is manually changed, it is not safe to cast its type)
* add tests
Diffstat (limited to 'src/components/organisms')
| -rw-r--r-- | src/components/organisms/forms/ackee-toggle/ackee-toggle.tsx | 8 | ||||
| -rw-r--r-- | src/components/organisms/forms/motion-toggle/motion-toggle.tsx | 10 |
2 files changed, 13 insertions, 5 deletions
diff --git a/src/components/organisms/forms/ackee-toggle/ackee-toggle.tsx b/src/components/organisms/forms/ackee-toggle/ackee-toggle.tsx index 8ada948..a9c172b 100644 --- a/src/components/organisms/forms/ackee-toggle/ackee-toggle.tsx +++ b/src/components/organisms/forms/ackee-toggle/ackee-toggle.tsx @@ -15,6 +15,9 @@ import { type TooltipProps, } from '../../../molecules'; +const validator = (value: unknown): value is AckeeOptions => + value === 'full' || value === 'partial'; + export type AckeeToggleProps = Omit< SwitchProps, 'isInline' | 'items' | 'name' | 'onSwitch' | 'value' @@ -46,9 +49,10 @@ export const AckeeToggle: FC<AckeeToggleProps> = ({ ...props }) => { const intl = useIntl(); - const { value, setValue } = useLocalStorage<AckeeOptions>( + const [value, setValue] = useLocalStorage( storageKey, - defaultValue + defaultValue, + validator ); const [isTooltipOpened, setIsTooltipOpened] = useState(false); diff --git a/src/components/organisms/forms/motion-toggle/motion-toggle.tsx b/src/components/organisms/forms/motion-toggle/motion-toggle.tsx index c141bf0..2545c20 100644 --- a/src/components/organisms/forms/motion-toggle/motion-toggle.tsx +++ b/src/components/organisms/forms/motion-toggle/motion-toggle.tsx @@ -10,6 +10,9 @@ import { export type MotionToggleValue = 'on' | 'off'; +const validator = (value: unknown): value is boolean => + typeof value === 'boolean'; + export type MotionToggleProps = Omit< SwitchProps, 'isInline' | 'items' | 'name' | 'onSwitch' | 'value' @@ -17,7 +20,7 @@ export type MotionToggleProps = Omit< /** * True if motion should be reduced by default. */ - defaultValue: 'on' | 'off'; + defaultValue: MotionToggleValue; /** * The local storage key to save preference. */ @@ -35,9 +38,10 @@ export const MotionToggle: FC<MotionToggleProps> = ({ ...props }) => { const intl = useIntl(); - const { value: isReduced, setValue: setIsReduced } = useLocalStorage<boolean>( + const [isReduced, setIsReduced] = useLocalStorage( storageKey, - defaultValue !== 'on' + defaultValue !== 'on', + validator ); useAttributes({ element: |
