All files / repo/src/hooks useLocalStorage.ts

100% Statements 27/27
100% Branches 5/5
100% Functions 3/3
100% Lines 27/27

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 331x   1x 9x   9x 9x 3x 3x 3x 1x 1x 3x   9x 9x 9x 5x 5x 9x 9x   9x 2x 2x 2x   9x 9x 9x 9x 9x  
import { ref, watch } from 'vue';
 
export function useLocalStorage<T>(key: string, defaultValue: T) {
  const data = ref<T>(defaultValue);
 
  const raw = localStorage.getItem(key);
  if (raw) {
    try {
      data.value = JSON.parse(raw);
    } catch (e) {
      console.warn(`Cannot parse data from localStorage under key '${key}':`, e);
    }
  }
 
  watch(
    data,
    (newVal) => {
      localStorage.setItem(key, JSON.stringify(newVal));
    },
    { deep: true }
  );
 
  function clear() {
    localStorage.removeItem(key);
    data.value = defaultValue;
  }
 
  return {
    data,
    clear,
  };
}