langfuse

Форк
0
/
useLocalStorage.tsx 
59 строк · 1.9 Кб
1
import { 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
 */
21
function useLocalStorage<T>(localStorageKey: string, initialValue: T) {
22
  const [value, setValue] = useState<T>(() => {
23
    if (typeof window === "undefined") {
24
      return initialValue;
25
    }
26
    try {
27
      const storedValue = localStorage.getItem(localStorageKey);
28
      return storedValue ? (JSON.parse(storedValue) as T) : initialValue;
29
    } catch (error) {
30
      console.error("Error reading from local storage", error);
31
      return initialValue;
32
    }
33
  });
34

35
  const clearValue = () => {
36
    try {
37
      localStorage.removeItem(localStorageKey);
38
      setValue(initialValue);
39
    } catch (error) {
40
      console.error("Error clearing local storage", error);
41
    }
42
  };
43

44
  useEffect(() => {
45
    try {
46
      localStorage.setItem(localStorageKey, JSON.stringify(value));
47
    } catch (error) {
48
      console.error("Error writing to local storage", error);
49
    }
50
  }, [localStorageKey, value]);
51

52
  return [value, setValue, clearValue] as [
53
    T,
54
    React.Dispatch<React.SetStateAction<T>>,
55
    () => void,
56
  ];
57
}
58

59
export default useLocalStorage;
60

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.