All files / react-app/src/hooks useLocalStorage.ts

96% Statements 24/25
83.33% Branches 10/12
100% Functions 5/5
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                      72x 5x 1x   4x       72x 3559x 471x 471x 471x 471x 470x   1x 1x       3559x 633x 633x 633x 633x 633x   632x   632x   1x         633x     3559x    
import { useState, useEffect } from "react";
 
interface LocalStorageData {
  osQuery?: string;
  osColumns?: string[];
  osDashboardData?: object;
  [key: string]: any;
}
 
type LocalStorageKeys = Extract<keyof LocalStorageData, string>;
 
export const removeItemLocalStorage = (key?: LocalStorageKeys) => {
  if (key) {
    window.localStorage.removeItem(key);
  } else {
    window.localStorage.removeItem("osData");
  }
};
 
export const useLocalStorage = (key: LocalStorageKeys, initialValue: any) => {
  const [storedValue, setStoredValue] = useState(() => {
    Iif (typeof window === "undefined") return initialValue;
    try {
      const item = window.localStorage.getItem("osData");
      const data = item ? JSON.parse(item) : {};
      return data[key] ?? initialValue;
    } catch (e) {
      console.log("Error while getting local storage: ", e);
      return initialValue;
    }
  });
 
  useEffect(() => {
    const updateLocalStorage = () => {
      Eif (typeof window !== "undefined") {
        try {
          const item = window.localStorage.getItem("osData");
          const data = item ? JSON.parse(item) : {};
 
          data[key] = storedValue;
 
          localStorage.setItem("osData", JSON.stringify(data));
        } catch (e) {
          console.log("Error setting local storage", e);
        }
      }
    };
 
    updateLocalStorage();
  }, [key, storedValue]);
 
  return [storedValue, setStoredValue];
};