Skip to content

Commit

Permalink
fix(useLocalStorage): using undefined for empty value instead of null
Browse files Browse the repository at this point in the history
  • Loading branch information
suyingtao committed Dec 16, 2019
1 parent 587de16 commit 1620e01
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,22 @@ type Dispatch<A> = (value: A) => void;
type SetStateAction<S> = S | ((prevState: S) => S);

const noop = () => {};
const isUndefined = (value?: any): boolean => typeof value === 'undefined';

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

const [state, setState] = useState<T | null>(() => {
const [state, setState] = useState<T | undefined>(() => {
try {
const localStorageValue = localStorage.getItem(key);
if (typeof initialValue === 'undefined' && typeof localStorageValue !== 'string') {
return null;
if (isUndefined(initialValue)) {
return undefined;
}
if (typeof localStorageValue !== 'string') {
localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
Expand All @@ -37,15 +38,15 @@ const useLocalStorage = <T>(
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
setState(null);
setState(undefined);
} catch {
// If user is in private mode or has storage restriction
// localStorage can throw.
}
}, [key, setState]);

useEffect(() => {
if (state === null) return;
if (isUndefined(state)) return;
try {
const serializedState = raw ? String(state) : JSON.stringify(state);
localStorage.setItem(key, serializedState);
Expand Down

0 comments on commit 1620e01

Please sign in to comment.