DEV Community

Ibrahim
Ibrahim

Posted on

How to Persist Pinia State

Sometimes, we want to persist the Pinia state so that when the page is closed, the state still exists when the page is restored. This can be useful for states like authentication tokens, shopping carts, and more.

This can be implemented using a plugin called Pinia Plugin Persistedstate.

This plugin persists Pinia store state using localStorage or other storage options.

To get started, install the plugin first:

npm install pinia-plugin-persistedstate
Enter fullscreen mode Exit fullscreen mode

Next, import the plugin and use it with the Pinia instance:

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
Enter fullscreen mode Exit fullscreen mode

Next, add the { persist: true } option to the store that should be persisted:

import { ref } from "vue";
import { defineStore } from "pinia";

export const useStore = defineStore(
  "auth",
  () => {
    const loggedIn = ref(false);
    const accessToken = ref(null);

    return { loggedIn, accessToken };
  },
  { persist: true }
);

Enter fullscreen mode Exit fullscreen mode

In the example above, the auth store's state will be automatically saved to localStorage.


For advanced usage, such as customizing the storage, read the full documentation at https://prazdevs.github.io/pinia-plugin-persistedstate.

Top comments (0)