Skip to content

Instantly share code, notes, and snippets.

@tohagan
Last active September 11, 2024 03:12
Show Gist options
  • Save tohagan/4f3a83892a3d57a197d7cf891625096b to your computer and use it in GitHub Desktop.
Save tohagan/4f3a83892a3d57a197d7cf891625096b to your computer and use it in GitHub Desktop.
Vue/Quasar: Persist a ref value to local storage
// 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