Seb-L/pinia-plugin-persist

How to use with Vue 3

oivvio opened this issue · 2 comments

The docs have instruction for how to use this plugin with Vue 2 and Nuxt but nothing for Vue 3.

Thanks for writing this plugin.

Same. My store is defined like this:

export const useUserStore = defineStore('user', () => {
  const name = ref('')
  const email = ref('')
  const role = ref('user')
  const apiKey = ref('')

  const getName = computed(() => name)
  const getemail = computed(() => email)
  const getRole = computed(() => role)
  const getApiKey = computed(() => apiKey)
  const isLoggedIn = computed(() => !!apiKey)

  function setName(userName: string) {
    name.value = userName
  }

  function setEmail(userEmail: string) {
    email.value = userEmail
  }

  function setApiKey(userApiKey: string) {
    apiKey.value = userApiKey
  }

  const cookiesStorage: Storage = {
    setItem(key, state) {
      return Cookies.set('accessToken', apiKey.value, { expires: 7 })
    },
    getItem(key) {
      return JSON.stringify({
        accessToken: Cookies.getJSON('accessToken'),
      })
    },
  }

  return {
    setName,
    setEmail,
    setApiKey,
    getName,
    getemail,
    getRole,
    getApiKey,
    isLoggedIn,
  }
})

How do I use this persist plugin?

Seb-L commented

I did not try the plugin with the "function" method of defining a store, but based on what I see in the sources of Pinia, the third argument of defineStore is the store options.

/**
 * Creates a `useStore` function that retrieves the store instance
 *
 * @param id - id of the store (must be unique)
 * @param storeSetup - function that defines the store
 * @param options - extra options
 */
export declare function defineStore<Id extends string, SS>(id: Id, storeSetup: () => SS, options?: DefineSetupStoreOptions<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>): StoreDefinition<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>;

You might be able to use it like so:

defineStore('myStore', () => {
  return {}
}, {
  persist: {
    enabled: true,
    ...
  },
})

I'll try it out, and I'll add it to the documentation.