mirror of
https://github.com/stefanpejcic/openpanel
synced 2025-06-26 18:28:26 +00:00
packages
This commit is contained in:
42
packages/devtools-ui/src/hooks/use-local-storage.test.ts
Normal file
42
packages/devtools-ui/src/hooks/use-local-storage.test.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useLocalStorage } from "./use-local-storage";
|
||||
import { getLocalStorage, setLocalStorage } from "../utils/local-storage";
|
||||
|
||||
jest.mock("../utils/local-storage");
|
||||
|
||||
describe("useLocalStorage", () => {
|
||||
const name = "test";
|
||||
const defaultValue = "default";
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return the default value if localStorage is empty", () => {
|
||||
(getLocalStorage as jest.Mock).mockReturnValueOnce(defaultValue);
|
||||
const { result } = renderHook(() =>
|
||||
useLocalStorage({ name, defaultValue }),
|
||||
);
|
||||
expect(result.current[0]).toEqual(defaultValue);
|
||||
});
|
||||
|
||||
it("should return the value from localStorage if available", () => {
|
||||
const value = "value";
|
||||
(getLocalStorage as jest.Mock).mockReturnValueOnce(value);
|
||||
const { result } = renderHook(() =>
|
||||
useLocalStorage({ name, defaultValue }),
|
||||
);
|
||||
expect(result.current[0]).toEqual(value);
|
||||
});
|
||||
|
||||
it("should update the value in localStorage when setValue is called", () => {
|
||||
const value = "value";
|
||||
const { result } = renderHook(() =>
|
||||
useLocalStorage({ name, defaultValue }),
|
||||
);
|
||||
act(() => {
|
||||
result.current[1](value);
|
||||
});
|
||||
expect(setLocalStorage).toHaveBeenCalledWith(name, value);
|
||||
});
|
||||
});
|
||||
19
packages/devtools-ui/src/hooks/use-local-storage.ts
Normal file
19
packages/devtools-ui/src/hooks/use-local-storage.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getLocalStorage, setLocalStorage } from "../utils/local-storage";
|
||||
|
||||
type Props<T> = {
|
||||
name: string;
|
||||
defaultValue: T;
|
||||
};
|
||||
|
||||
export const useLocalStorage = <T>({ name, defaultValue }: Props<T>) => {
|
||||
const [value, setValue] = useState<T>(() => {
|
||||
return getLocalStorage(name, defaultValue);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setLocalStorage(name, value);
|
||||
}, [value]);
|
||||
|
||||
return [value, setValue] as const;
|
||||
};
|
||||
Reference in New Issue
Block a user