Last active
September 11, 2024 03:12
-
-
Save tohagan/4f3a83892a3d57a197d7cf891625096b to your computer and use it in GitHub Desktop.
Vue/Quasar: Persist a ref value to local storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Persist a ref value to local storage | |
// Quasar performs the conversion to/from the data type T | |
// https://quasar.dev/quasar-plugins/web-storage#localstorage-api | |
// usePersistedRef.ts | |
import { watch, Ref } from 'vue'; | |
import { LocalStorage } from 'quasar'; | |
export function usePersistedRef<T>(key: string, ref: Ref<T>): Ref<T> { | |
const storedValue = LocalStorage.getItem(key) as T | |
// Watch for changes to the value and persist them to LocalStorage | |
watch(ref, (newValue) => { | |
LocalStorage.set(key, newValue); | |
}); | |
// If there is a stored value, update the passed ref with it | |
if (storedValue !== null) { | |
ref.value = storedValue; | |
} | |
return ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment