All files / utils useLocalStorage.js

100% Statements 16/16
100% Branches 2/2
100% Functions 3/3
100% Lines 16/16

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                    1x 7x 5x 5x 4x 2x 2x   2x   1x 1x       7x 2x 2x 2x   1x       7x        
// See: https://www.youtube.com/watch?v=vRDGUUEg_n8 for an explanation
// This hook creates a drop in replacement for useState that syncs
// the state with local storage. It will take a key and an initial value,
// and return an array with the current value and a function to update it.
 
// The initial value is used only in the case that the key
// is not already in local storage.
 
import { useState } from "react";
 
const useLocalStorage = (key, initialValue) => {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key);
      if (item === null) {
        localStorage.setItem(key, JSON.stringify(initialValue));
        return initialValue;
      }
      return JSON.parse(item);
    } catch (error) {
      console.error("Error: when useLocalStorage called useState", error);
      return null;
    }
  });
 
  const setValue = (value) => {
    try {
      setStoredValue(value);
      localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error("Error: in setter generated by useLocalStorage", error);
    }
  };
 
  return [storedValue, setValue];
};
 
export default useLocalStorage;