running-tools

A collection of tools for runners and their coaches
git clone https://git.ashermorgan.net/running-tools/
Log | Files | Refs | README

useStorage.ts (1003B)


      1 import { ref, onActivated, watchEffect } from 'vue';
      2 import type { Ref } from 'vue';
      3 
      4 import { deepCopy, getLocalStorage, setLocalStorage } from '@/core/utils';
      5 
      6 /*
      7  * Create a reactive value that is synced with a localStorage item
      8  * @param {string} key The localStorage item's key
      9  * @param {Type} defaultValue The default value
     10  * @returns {Ref<Type>} The synchronized ref
     11  */
     12 export default function useStorage<Type>(key: string, defaultValue: Type): Ref<Type> {
     13   const clonedDefault: Type = deepCopy(defaultValue);
     14   const value: Ref<Type> = ref<Type>(clonedDefault) as Ref<Type>;
     15 
     16   // (Re)load value from localStorage
     17   function updateValue() {
     18     const parsedValue = getLocalStorage<Type>(key);
     19     if (parsedValue !== null) value.value = parsedValue;
     20   }
     21   updateValue();
     22   onActivated(updateValue);
     23 
     24   // Save value to localStorage when modified
     25   watchEffect(() => {
     26     if (typeof localStorage !== 'undefined') {
     27       setLocalStorage<Type>(key, value.value);
     28     }
     29   })
     30 
     31   return value
     32 }