langfuse
59 строк · 1.9 Кб
1import { useState, useEffect } from "react";
2
3/**
4* useLocalStorage is a hook for managing data with the localStorage API.
5*
6* @param {string} localStorageKey - The key under which the value is stored in localStorage.
7* @param {T} initialValue - The initial value of the data to be stored.
8*
9* Note: The object T should be able to be stringified, as it will be stored in localStorage as a string.
10*
11* @return An array with three elements:
12* value: Current value
13* setValue: Function to update the value
14* clearValue: Function to remove value from the local storage.
15* This function will also reset the value to initial value
16*
17* @template T - The type of the data to be stored in localStorage. It should be a type that can be stringified.
18*
19* @throws Will throw an error if the stringifying the value or accessing local storage fails.
20*/
21function useLocalStorage<T>(localStorageKey: string, initialValue: T) {
22const [value, setValue] = useState<T>(() => {
23if (typeof window === "undefined") {
24return initialValue;
25}
26try {
27const storedValue = localStorage.getItem(localStorageKey);
28return storedValue ? (JSON.parse(storedValue) as T) : initialValue;
29} catch (error) {
30console.error("Error reading from local storage", error);
31return initialValue;
32}
33});
34
35const clearValue = () => {
36try {
37localStorage.removeItem(localStorageKey);
38setValue(initialValue);
39} catch (error) {
40console.error("Error clearing local storage", error);
41}
42};
43
44useEffect(() => {
45try {
46localStorage.setItem(localStorageKey, JSON.stringify(value));
47} catch (error) {
48console.error("Error writing to local storage", error);
49}
50}, [localStorageKey, value]);
51
52return [value, setValue, clearValue] as [
53T,
54React.Dispatch<React.SetStateAction<T>>,
55() => void,
56];
57}
58
59export default useLocalStorage;
60