Skip to content

Instantly share code, notes, and snippets.

@monsat
Created May 14, 2023 14:08
Show Gist options
  • Save monsat/ffa9bb9a9ec3983391f41669393a2ede to your computer and use it in GitHub Desktop.
Save monsat/ffa9bb9a9ec3983391f41669393a2ede to your computer and use it in GitHub Desktop.
Nuxt useState with VueUse useStorage composables
import { useStorage } from '@vueuse/core'
export const useStoredState = <T>(key: string, initValue: T) => {
const shared = useState<T>(key, () => initValue)
const stored = useStorage<T>(key, initValue)
const state = computed({
get: () => shared.value,
set: (value: T) => {
shared.value = value
stored.value = value
},
})
// call read() onMounted in app.vue
const read = () => {
state.value = stored.value
}
return {
state,
read,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment