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

86.66% Statements 13/15
66.66% Branches 4/6
100% Functions 3/3
92.85% Lines 13/14

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    80x 3828x 481x 481x 481x 481x   1x 1x       3828x 646x 646x 646x             3828x    
import { useEffect, useState } from "react";
 
export const useLocalStorage = <T>(key: string, initialValue: T) => {
  const [storedValue, setStoredValue] = useState<T>(() => {
    Iif (typeof window === "undefined") return initialValue;
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (e) {
      console.log("Error while getting local storage:", e);
      return initialValue;
    }
  });
 
  useEffect(() => {
    Eif (typeof window !== "undefined") {
      try {
        window.localStorage.setItem(key, JSON.stringify(storedValue));
      } catch (e) {
        console.log("Error setting local storage:", e);
      }
    }
  }, [key, storedValue]);
 
  return [storedValue, setStoredValue] as const;
};