Skip to content
Open
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
12 changes: 7 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
type Serializer<T> = (object: T | undefined) => string;
type Parser<T> = (val: string) => T | undefined;
type Setter<T> = React.Dispatch<React.SetStateAction<T | undefined>>;
type DefaultValue<T> = T | (() => T)

type Options<T> = Partial<{
serializer: Serializer<T>;
Expand All @@ -13,12 +14,12 @@ type Options<T> = Partial<{

function useLocalStorage<T>(
key: string,
defaultValue: T,
defaultValue: DefaultValue<T>,
options?: Options<T>
): [T, Setter<T>];
function useLocalStorage<T>(
key: string,
defaultValue?: T,
defaultValue?: DefaultValue<T>,
options?: Options<T>
) {
const opts = useMemo(() => {
Expand All @@ -36,17 +37,18 @@ function useLocalStorage<T>(
const rawValueRef = useRef<string | null>(null);

const [value, setValue] = useState(() => {
if (typeof window === "undefined") return defaultValue;
const newValue = defaultValue instanceof Function ? defaultValue() : defaultValue
if (typeof window === "undefined") return newValue;

try {
rawValueRef.current = window.localStorage.getItem(key);
const res: T = rawValueRef.current
? parser(rawValueRef.current)
: defaultValue;
: newValue;
return res;
} catch (e) {
logger(e);
return defaultValue;
return newValue;
}
});

Expand Down
9 changes: 9 additions & 0 deletions test/useLocalStorage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ export function TestComponent() {
);
}

function WithLazyInitialState({ text }: { text: string }) {
const [data] = useLocalStorage("username", () => text);
return <p>{data}</p>;
}

function WithCustomParser() {
const [data] = useLocalStorage("username", "John Doe", {
parser: (val) => JSON.parse(val) + "kraw",
Expand Down Expand Up @@ -174,6 +179,10 @@ describe("useLocalStorage", () => {
JSON.stringify("foobarbarbarbar")
);
});
it("uses a lazy initial state", () => {
const { container } = render(<WithLazyInitialState text="johndoe85kraw" />);
expect(container.querySelector("p")).toHaveTextContent("johndoe85kraw");
});
it("uses a custom parser", () => {
localStorage.setItem("username", JSON.stringify("johndoe85"));
const { container } = render(<WithCustomParser />);
Expand Down