pinia-plugin-persistedstate icon indicating copy to clipboard operation
pinia-plugin-persistedstate copied to clipboard

Persistence doesn't work?

Open xMaxximum opened this issue 1 year ago • 3 comments

Describe the bug

Hello, I wanted to try this out. Below is minimum reproducible code. Using Nuxt 3. The store loses its state after seemingly refreshing or going to another page. It also doesn't save it to cookies as it should. calling store.$persist() throws an error saying it doesn't exist.

What have I done wrong? Used this for reference: https://prazdevs.github.io/pinia-plugin-persistedstate/frameworks/nuxt-3.html

nuxt.config.ts:

export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: [
    "@nuxt/ui",
    "@pinia/nuxt", // needed
    "@pinia-plugin-persistedstate/nuxt",
  ],
  ui: {
    icons: ["tdesign"],
  },
  piniaPersistedstate: {
    cookieOptions: {
      expires: new Date(new Date().getTime() + 400 * 24 * 60 * 60 * 1000),
    },
    storage: "cookies",
    debug: true,
  },
  build: {
    transpile: ["pinia-plugin-persistedstate"],
  },
});

stores/account.ts

import { defineStore } from "pinia";

export const useAccountStore = defineStore({
  id: "accountStore",
  state: () => {
    const email = ref("");
    const password = ref("");
    const role = ref("");

    return { email, password, role };
  },
  actions: {},
});

login.vue

<script setup lang="ts">
const store = useAccountStore();

// fetch request somewhere

const res = await response.json();
      store.$patch({ // updated store inside vue edge browser extension but not in the cookie
        email: res.email,
        password: res.password,
        role: res.userrole
      })

</script>

Reproduction

https://stackblitz.com/edit/nuxt-starter-gpnkto?file=app.vue

System Info

System:
    OS: Windows 11 10.0.22621
    CPU: (24) x64 13th Gen Intel(R) Core(TM) i7-13700K
    Memory: 12.25 GB / 31.78 GB
  Binaries:
    Node: 21.5.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.2.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (121.0.2277.83)
    Internet Explorer: 11.0.22621.1

Used Package Manager

npm

Validations

xMaxximum avatar Jan 29 '24 20:01 xMaxximum

Facing the same issue even after switching to localstorage on nuxt global config.

vis97c avatar Feb 07 '24 00:02 vis97c

Facing the same issue even after switching to localstorage on nuxt global config.

Hey, turns out global config can be completely ignored. I added my persistence config to my store directly and it works now.

xMaxximum avatar Feb 07 '24 06:02 xMaxximum

You must add the persist property to your store with a boolean value and by default it will save the value in the cookies

image

sebastiandotdev avatar Feb 28 '24 22:02 sebastiandotdev