Skip to content

Commit

Permalink
fix: useLocalStorage overload for correct undefined behavior
Browse files Browse the repository at this point in the history
Fixes streamich#2551

Instead of using a single function which accepts `defaultValue?: T` - which forces a return type of `T | undefined`, use an overload. When a defaultValue is supplied, the useState-like tuple returned uses `T`. When no defaultValue is supplied, it's `T | undefined`.

Runtime usage is exaclty the same, this just improves the types.
  • Loading branch information
mmkal committed Apr 25, 2024
1 parent ade8d39 commit 3083f50
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,21 @@ type parserOptions<T> =
deserializer: (value: string) => T;
};

const useLocalStorage = <T>(
function useLocalStorage<T>(
key: string,
initialValue: T,
options?: parserOptions<T>
): [T, Dispatch<SetStateAction<T>>, () => void];
function useLocalStorage<T>(
key: string,
initialValue?: undefined,
options?: parserOptions<T>
): [T | undefined, Dispatch<SetStateAction<T | undefined>>, () => void];
function useLocalStorage<T>(
key: string,
initialValue?: T,
options?: parserOptions<T>
): [T | undefined, Dispatch<SetStateAction<T | undefined>>, () => void] => {
): [T | undefined, Dispatch<SetStateAction<T | undefined>>, () => void] {
if (!isBrowser) {
return [initialValue as T, noop, noop];
}
Expand Down Expand Up @@ -94,6 +104,6 @@ const useLocalStorage = <T>(
}, [key, setState]);

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

export default useLocalStorage;

0 comments on commit 3083f50

Please sign in to comment.