Created
October 30, 2022 05:50
-
-
Save monsat/c6b8a5bf0e8ba360086b82bef4c7ea9f to your computer and use it in GitHub Desktop.
Add commit/restore storage method to Vue.js global state Ref
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
import { ref } from 'vue-demi' | |
import type { Ref, UnwrapRef } from 'vue-demi' | |
import { createGlobalState, useSessionStorage } from '@vueuse/core' | |
export type StorableRef<T> = Ref<T> & { | |
commit: () => void | |
restore: () => void | |
} | |
const createState = <T>(storageKey: string, initialValue: T) => createGlobalState(() => useSessionStorage(storageKey, initialValue)) | |
export function storableRef<T>(storageKey: string, initialValue: T): StorableRef<T> { | |
const actual = ref(initialValue) as Ref<T> | |
const stored = createState<T>(storageKey, initialValue)() | |
const commit = () => { | |
stored.value = actual.value | |
} | |
const restore = () => { | |
actual.value = stored.value | |
} | |
Object.defineProperties(actual, { | |
commit: { | |
value: commit, | |
}, | |
restore: { | |
value: restore, | |
}, | |
}) | |
// read from storage on mount | |
restore() | |
return actual as StorableRef<T> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: