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(useLocalStorage): add remove method. (#229) #835

Merged
merged 2 commits into from
Jan 5, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion docs/useLocalStorage.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ React side-effect hook that manages a single `localStorage` key.
import {useLocalStorage} from 'react-use';

const Demo = () => {
const [value, setValue] = useLocalStorage('my-key', 'foo');
const [value, setValue, remove] = useLocalStorage('my-key', 'foo');

return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue('bar')}>bar</button>
<button onClick={() => setValue('baz')}>baz</button>
<button onClick={() => remove()}>Remove</button>
</div>
);
};
Expand Down
34 changes: 26 additions & 8 deletions src/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { isClient } from './util';

type Dispatch<A> = (value: A) => void;
type SetStateAction<S> = S | ((prevState: S) => S);

const useLocalStorage = <T>(key: string, initialValue?: T, raw?: boolean): [T, Dispatch<SetStateAction<T>>] => {
const noop = () => {};

const useLocalStorage = <T>(
key: string,
initialValue?: T,
raw?: boolean
): [T | null, Dispatch<SetStateAction<T | null>>, () => void] => {
if (!isClient) {
return [initialValue as T, () => {}];
return [initialValue as T, noop, noop];
}

const [state, setState] = useState<T>(() => {
const [state, setState] = useState<T | null>(() => {
try {
const localStorageValue = localStorage.getItem(key);
if (typeof initialValue === 'undefined' && typeof localStorageValue !== 'string') {
return null;
}
if (typeof localStorageValue !== 'string') {
localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
return initialValue;
} else {
return raw ? localStorageValue : JSON.parse(localStorageValue || 'null');
}
return raw ? localStorageValue : JSON.parse(localStorageValue || 'null');
} catch {
// If user is in private mode or has storage restriction
// localStorage can throw. JSON.parse and JSON.stringify
Expand All @@ -26,7 +34,18 @@ const useLocalStorage = <T>(key: string, initialValue?: T, raw?: boolean): [T, D
}
});

const remove = useCallback(() => {
try {
localStorage.removeItem(key);
setState(null);
} catch {
// If user is in private mode or has storage restriction
// localStorage can throw.
}
}, [key, setState]);

useEffect(() => {
if (state === null) return;
try {
const serializedState = raw ? String(state) : JSON.stringify(state);
localStorage.setItem(key, serializedState);
Expand All @@ -35,8 +54,7 @@ const useLocalStorage = <T>(key: string, initialValue?: T, raw?: boolean): [T, D
// localStorage can throw. Also JSON.stringify can throw.
}
}, [state]);

return [state, setState];
return [state, setState, remove];
};

export default useLocalStorage;
7 changes: 7 additions & 0 deletions stories/useLocalStorage.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ import ShowDocs from './util/ShowDocs';

const Demo = () => {
const [value, setValue] = useLocalStorage('hello-key', 'foo');
const [removableValue, setRemovableValue, remove] = useLocalStorage('removeable-key');

return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue('bar')}>bar</button>
<button onClick={() => setValue('baz')}>baz</button>
<br />
<br />
<div>Removable Value: {removableValue}</div>
<button onClick={() => setRemovableValue('foo')}>foo</button>
<button onClick={() => setRemovableValue('bar')}>bar</button>
<button onClick={() => remove()}>Remove</button>
</div>
);
};
Expand Down