Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useStorage): Add isEnabled option to useStorage/useLocalStorage/useSessionStorage via refactor to use options objects #140

Merged
merged 2 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/hooks/useStorage/useLocalStorage.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ and it supports TypeScript [generics](https://www.typescriptlang.org/docs/handbo
infer its return types based on the `defaultValue`.

```ts
const [value, setValue] = useLocalStorage<T>(key: string, defaultValue: T);
const [value, setValue] = useLocalStorage<T>({ key: string, defaultValue: T });
```

## Notes
Expand Down
31 changes: 22 additions & 9 deletions src/hooks/useStorage/useLocalStorage.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ValidatedTextInput } from '../../components/ValidatedTextInput';
import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon';

export const PersistentCounterExample: React.FunctionComponent = () => {
const [count, setCount] = useLocalStorage('exampleCounter', 0);
const [count, setCount] = useLocalStorage({ key: 'exampleCounter', defaultValue: 0 });
return (
<NumberInput
value={count}
Expand All @@ -36,7 +36,7 @@ export const PersistentCounterExample: React.FunctionComponent = () => {
};

export const PersistentTextFieldExample: React.FunctionComponent = () => {
const [value, setValue] = useLocalStorage('exampleTextField', '');
const [value, setValue] = useLocalStorage({ key: 'exampleTextField', defaultValue: '' });
return (
<TextInput
aria-label="Persistent text field example input"
Expand All @@ -47,7 +47,10 @@ export const PersistentTextFieldExample: React.FunctionComponent = () => {
};

export const PersistentCheckboxExample: React.FunctionComponent = () => {
const [isChecked, setIsChecked] = useLocalStorage('exampleCheckboxChecked', false);
const [isChecked, setIsChecked] = useLocalStorage({
key: 'exampleCheckboxChecked',
defaultValue: false,
});
return (
<Checkbox
id="checkbox-example"
Expand All @@ -60,7 +63,10 @@ export const PersistentCheckboxExample: React.FunctionComponent = () => {

export const WelcomeModalExample: React.FunctionComponent = () => {
const ExamplePage: React.FunctionComponent = () => {
const [isModalDisabled, setIsModalDisabled] = useLocalStorage('welcomeModalDisabled', false);
const [isModalDisabled, setIsModalDisabled] = useLocalStorage({
key: 'welcomeModalDisabled',
defaultValue: false,
});
const [isModalOpen, setIsModalOpen] = React.useState(!isModalDisabled);
return (
<>
Expand Down Expand Up @@ -121,7 +127,10 @@ export const WelcomeModalExample: React.FunctionComponent = () => {
export const ReusedKeyExample: React.FunctionComponent = () => {
// In a real app each of these components would be in separate files.
const ComponentA: React.FunctionComponent = () => {
const [value, setValue] = useLocalStorage('exampleReusedKey', 'default value here');
const [value, setValue] = useLocalStorage({
key: 'exampleReusedKey',
defaultValue: 'default value here',
});
return (
<div className={spacing.mbLg}>
<TextContent className={spacing.mbSm}>
Expand All @@ -136,7 +145,10 @@ export const ReusedKeyExample: React.FunctionComponent = () => {
);
};
const ComponentB: React.FunctionComponent = () => {
const [value] = useLocalStorage('exampleReusedKey', 'default value here');
const [value] = useLocalStorage({
key: 'exampleReusedKey',
defaultValue: 'default value here',
});
return (
<div className={spacing.mbLg}>
<TextContent className={spacing.mbSm}>
Expand All @@ -157,7 +169,8 @@ export const ReusedKeyExample: React.FunctionComponent = () => {

export const CustomHookExample: React.FunctionComponent = () => {
// This could be exported from its own file and imported in multiple component files.
const useMyStoredValue = () => useLocalStorage('myStoredValue', 'default defined once');
const useMyStoredValue = () =>
useLocalStorage({ key: 'myStoredValue', defaultValue: 'default defined once' });

// In a real app each of these components would be in separate files.
const ComponentA: React.FunctionComponent = () => {
Expand All @@ -176,7 +189,7 @@ export const CustomHookExample: React.FunctionComponent = () => {
);
};
const ComponentB: React.FunctionComponent = () => {
const [value] = useLocalStorage('exampleReusedKey', 'default value here');
const [value] = useMyStoredValue();
return (
<div className={spacing.mbLg}>
<TextContent className={spacing.mbSm}>
Expand All @@ -197,7 +210,7 @@ export const CustomHookExample: React.FunctionComponent = () => {

export const ComplexValueExample: React.FunctionComponent = () => {
type Item = { name: string; description?: string };
const [items, setItems] = useLocalStorage<Item[]>('exampleArray', []);
const [items, setItems] = useLocalStorage<Item[]>({ key: 'exampleArray', defaultValue: [] });

const addForm = useFormState({
name: useFormField('', yup.string().required().label('Name')),
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useStorage/useSessionStorage.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ and it supports TypeScript [generics](https://www.typescriptlang.org/docs/handbo
infer its return types based on the `defaultValue`.

```ts
const [value, setValue] = useSessionStorage<T>(key: string, defaultValue: T);
const [value, setValue] = useSessionStorage<T>({ key: string, defaultValue: T });
```

## Notes
Expand Down
6 changes: 3 additions & 3 deletions src/hooks/useStorage/useSessionStorage.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { ValidatedTextInput } from '../../components/ValidatedTextInput';
import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon';

export const PersistentCounterExample: React.FunctionComponent = () => {
const [count, setCount] = useSessionStorage('exampleCounter', 0);
const [count, setCount] = useSessionStorage({ key: 'exampleCounter', defaultValue: 0 });
return (
<NumberInput
value={count}
Expand All @@ -34,7 +34,7 @@ export const PersistentCounterExample: React.FunctionComponent = () => {
};

export const PersistentTextFieldExample: React.FunctionComponent = () => {
const [value, setValue] = useSessionStorage('exampleTextField', '');
const [value, setValue] = useSessionStorage({ key: 'exampleTextField', defaultValue: '' });
return (
<TextInput
aria-label="Persistent text field example input"
Expand All @@ -46,7 +46,7 @@ export const PersistentTextFieldExample: React.FunctionComponent = () => {

export const ComplexValueExample: React.FunctionComponent = () => {
type Item = { name: string; description?: string };
const [items, setItems] = useSessionStorage<Item[]>('exampleArray', []);
const [items, setItems] = useSessionStorage<Item[]>({ key: 'exampleArray', defaultValue: [] });

const addForm = useFormState({
name: useFormField('', yup.string().required().label('Name')),
Expand Down
41 changes: 25 additions & 16 deletions src/hooks/useStorage/useStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,30 +35,38 @@ const setValueInStorage = <T>(storageType: StorageType, key: string, newValue: T
}
};

const useStorage = <T>(
storageType: StorageType,
key: string,
defaultValue: T
): [T, React.Dispatch<React.SetStateAction<T>>] => {
interface IUseStorageOptions<T> {
isEnabled?: boolean;
type: StorageType;
key: string;
defaultValue: T;
}

const useStorage = <T>({
isEnabled = true,
type,
key,
defaultValue,
}: IUseStorageOptions<T>): [T, React.Dispatch<React.SetStateAction<T>>] => {
const [cachedValue, setCachedValue] = React.useState<T>(
getValueFromStorage(storageType, key, defaultValue)
getValueFromStorage(type, key, defaultValue)
);

const usingStorageEvents = storageType === 'localStorage' && typeof window !== 'undefined';
const usingStorageEvents = type === 'localStorage' && typeof window !== 'undefined' && isEnabled;

const setValue: React.Dispatch<React.SetStateAction<T>> = React.useCallback(
(newValueOrFn: T | ((prevState: T) => T)) => {
const newValue =
newValueOrFn instanceof Function
? newValueOrFn(getValueFromStorage(storageType, key, defaultValue))
? newValueOrFn(getValueFromStorage(type, key, defaultValue))
: newValueOrFn;
setValueInStorage(storageType, key, newValue);
setValueInStorage(type, key, newValue);
if (!usingStorageEvents) {
// The cache won't update automatically if there is no StorageEvent dispatched.
setCachedValue(newValue);
}
},
[storageType, key, defaultValue, usingStorageEvents]
[type, key, defaultValue, usingStorageEvents]
);

React.useEffect(() => {
Expand All @@ -77,12 +85,13 @@ const useStorage = <T>(
return [cachedValue, setValue];
};

export type UseStorageTypeOptions<T> = Omit<IUseStorageOptions<T>, 'type'>;

export const useLocalStorage = <T>(
key: string,
defaultValue: T
): [T, React.Dispatch<React.SetStateAction<T>>] => useStorage('localStorage', key, defaultValue);
options: UseStorageTypeOptions<T>
): [T, React.Dispatch<React.SetStateAction<T>>] => useStorage({ ...options, type: 'localStorage' });

export const useSessionStorage = <T>(
key: string,
defaultValue: T
): [T, React.Dispatch<React.SetStateAction<T>>] => useStorage('sessionStorage', key, defaultValue);
options: UseStorageTypeOptions<T>
): [T, React.Dispatch<React.SetStateAction<T>>] =>
useStorage({ ...options, type: 'sessionStorage' });
Loading