Last active
September 19, 2022 03:15
-
-
Save monsat/4c1eca1d6ea9766b03bc5e4894fe8271 to your computer and use it in GitHub Desktop.
useState Clone: Nuxt 3 useState composables for Nuxt 2 app
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' | |
import { createGlobalState, createSharedComposable } from '@vueuse/core' | |
const createBaseStore = <T>() => createGlobalState<Record<string, Ref<T>>>(() => reactive({})) | |
const useBaseStore = createSharedComposable(createBaseStore) | |
export const useState = <T>(key: string, init?: () => T): Ref<T> => { | |
const store = useBaseStore<T>() | |
const state = store[key] | |
if (state !== undefined) { | |
return state | |
} | |
const initialValue = ref(init()) as Ref<T> | |
store[key] = initialValue | |
return initialValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment