5

I am trying to persist the state of a variable in a fresh Nuxt 3 app by using the package pinia-plugin-persistedstate.

I've implemented the steps provided in the guide for nuxt 3:

  1. Created the /plugins/persistedstate.ts file.
  2. Added persist: true option in the store file.

But nothing is happening. Whenever I refresh the page the store value is getting lost.

Can someone please help me to understand what is the issue here? Also if someone has used the package please share the steps that I may be missing while implementation.

kissu
  • 40,416
  • 14
  • 65
  • 133
Gaurav Gusain
  • 76
  • 1
  • 4

4 Answers4

2

I have found this integration to work, but the problem is that a cookie can only be a certain size. That might be the problem. ie Your response object is bigger than the available size to store the data in the cookie

  • Refer to this post: https://stackoverflow.com/questions/72203619/nuxt3-pinia-vueuse-usestorage-not-working/73957331#73957331 I think I found a viable solution – Franco Labuschagne Oct 05 '22 at 07:58
1

I had the same issues and decided to go for a quick and easy workaround, without using any plugins:

// app.vue

<template>
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

<script setup>
import { watch, onBeforeMount } from "vue";
import { usePersistentStore } from "~~/store/persistent";

const ps = usePersistentStore();

onBeforeMount(() => {
  ps.$state = JSON.parse(localStorage.getItem("persistent"));
});
watch(ps.$state, (value) => {
  localStorage.setItem("persistent", JSON.stringify(ps.$state));
});
</script>
mrvnklm
  • 1,348
  • 2
  • 10
  • 19
0

This worked for me. Instead of using cookies which relies on useCookie composable of nuxt which seems to be having issues presently, select localstorage and turn off the ssr for the pages involved by using <client-side> ... </client-side> or globally on your nuxtjs.config

import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: 'hello pinia',
    }
  },
  persist: {
    storage: persistedState.localStorage,
  },
})


Here code sample: Then turn off Server side rendering Here a link to help https://prazdevs.github.io/pinia-plugin-persistedstate/frameworks/nuxt-3.html

0

As per the documentation here, for Nuxt3, the pinia persisted state plugin must be configured as a module in the nuxt.config.ts file:

export default defineNuxtConfig({
  modules: [
    '@pinia/nuxt',
    '@pinia-plugin-persistedstate/nuxt',
  ],
})

In Nuxt3, there is no need to create the /plugins/persistedstate.ts file.

rysama
  • 1,674
  • 16
  • 28