Code Monkey home page Code Monkey logo

pinia-plugin-persistedstate's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinia-plugin-persistedstate's Issues

Local storage expire time option

Hi thank you for the great plugin you provided for us to use , greate job just wanted to ask is there a way to make a store or a portion of it persistant for a limited amount of time ? thank you very much

[Help Needed] - Pinia not persisting to my quasar project with vite

Hi Newbie here,... i tried to install this plugin to my quasar project with vite but it doesn't seem working.

basically i followed the steps written to this plugin.

first is i import this plugin to my quasar app in src/stores/index.js

import { store } from 'quasar/wrappers'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Store instance.
 */

export default store((/* { ssrContext } */) => {
  const pinia = createPinia()
  
  // You can add Pinia plugins here
  // pinia.use(SomePiniaPlugin)
  pinia.use(piniaPluginPersistedstate)

  return pinia
})

Then i added the persist: true to my AuthStore

export const useAuth = defineStore('auth', {
  state: () => ({
    Authenticated: false,
    Auth: {
      token: null,
      user: {
        firstName: "Juan",
        lastName: "Dela Cruz",
        scopes: [
          "somescopes",
        ],
      },
    },
  }),
  
  getters: {
    getUser (state) {
      return state.Auth.user
    },
    getToken (state) {
      return state.Auth.token
    },
    getAuthStatus (state) {
      return state.Authenticated
    },
    getScopes (state) {
      return state.Auth.user.scopes
    }
  },
  
  actions: {
    setUser (data) {
      this.user = data
    }
  },
  persist: true,
})

then when i run my app i check my localStorage but it did not set the auth to localStorage

it seems like its working on webpack but i'm not sure with vite.

Provide a way to change default plugin options

Issue: Currently there is no way to use sessionStorage (for example) other than explicitly defining it in each store for each store property.

It would be useful if we had some way of setting default options for the plugin.

I've opened a PR #26 that exports an additional function which can take new default options. It should not break current plugin usage.

Docs / ReadMe needs updating to avoid downloading the wrong plugin

At the moment your docs say "Install with your favourite package manager (pnpm, npm, yarn)."

But because of many similar named packages it's easy to download the wrong one.

For example, these are all wrong, but have almost identical names. There are many more than these 3 examples:

To stop people downloading the wrong plugin I suggest you add links to the correct packages on your read me page instead of letting people search for the correct one.

For example: https://www.npmjs.com/package/pinia-plugin-persistedstate

Or just add the correct download command directly on the docs npm i pinia-plugin-persistedstate.

Thanks for such a great plugin. This is just my 2 cents to make things easier :)

References are getting lost

I'm not sure if there is a fix for this and maybe it is a very specific case, but I have the following problem.

I create an object and add it to a list and a dictionary at the same time like so:

state: () => {
  itemList: [],
  itemDict: {},
}

actions: {
  addItem(data: {id: number, ...}) {
    const newItem = data
    newItem.createdDt = new Date()
    this.itemList.push(newItem)
    this.itemDict[data.id] = newItem
  }
}

Now, an item that is in the list and in the dict has the same reference, aka.

itemList[0] === itemDict[itemList[0].id] -> true

and they are reactive, meaning that if I update the item in either the list or the dict it will also update in the other.

After refreshing the page and restoring the store from local storage the objects are not the same anymore, aka.

itemList[0] === itemDict[itemList[0].id] -> false

Therefore reactivity between them is getting lost.

I assume a side effect of this is also that the data is getting duplicated, consuming double the storage.

A workout around for this specific problem would be hook that is called after restoring the state. That way I could exclude either the list or the dict from being persisted and recreated it upon restoration, something like this:

A workout around for this specific problem would be a hook that is called after restoring the state. That way I could exclude either the list or the dict from being persisted and recreate it upon restoration, something like this:

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => {
    return {
      itemList: [],
      itemDict: {},
    }
  },
  persist: {
    paths: [
      'itemList',
    ],
    afterRestore: ({ state }) => {
      state.itemDict = state.itemList.reduce((dict, item) => {
        dict[item.id] = item
        return dict
      } , {})
    }
  }
})

Vue 2 is still supported?

Hello!

I need to persist in my pinia state. I have installed this plugin but when starting I am getting this error:

vue-composition-api.mjs?d80b:34 Uncaught Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.
    at assert (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:88:15)
    at getVueConstructor (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:369:9)
    at eval (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:287:42)
    at withCurrentInstanceTrackingDisabled (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:401:9)
    at new EffectScope (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:286:9)
    at effectScope (webpack-internal:///../../shared/node_modules/@vue/composition-api/dist/vue-composition-api.mjs:309:12)
    at createPinia (webpack-internal:///../../shared/node_modules/pinia/dist/pinia.esm-bundler.js:887:79)
    at eval (webpack-internal:///../../shared/src/pinia/index.js:10:70)
    at Module.../../shared/src/pinia/index.js (app.js:1761:1)
    at __webpack_require__ (app.js:854:30)

My code is like this:

import { createPinia, PiniaPlugin } from 'pinia'
import Vue from 'vue'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import VueCompositionApi from '@vue/composition-api'

Vue.use(VueCompositionApi)
Vue.use(PiniaPlugin)

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

export { pinia }

I'm currently using Vue2, pinia version 2.0.0-rc.6 and pinia-plugin-persistedstate version 1.2.1.

Could someone help me get this to work in Vue2? thanks in advance

Local storage needs encryption

Local storage needs encryption. I hope to provide two hook functions,

I need to encrypt before saving

I need to decrypt before taking values

persisting pinia store within Quasar app

I'm trying to use this Pinia Plugin in my Quasar app (Vue 3 / TypeScript).

Out of the box everything works fine.

But when using a Quasar boot file the persisted state stops working. Refreshing the page wipes all the new values away.

I don't know why the boot file breaks the persisted state plugin, but I have narrowed the culprit down to a single line...

This is how I am using Pinia with Quasar and adding the plugin:

src/store/index.ts

/* eslint-disable @typescript-eslint/no-unused-vars */
import { store } from 'quasar/wrappers';
import { createPinia, Pinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

declare module '@quasar/app' {
  interface BootFileParams<TState> {
    store: Pinia;
  }
  interface PreFetchOptions<TState> {
    store: Pinia;
  }
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $store: import('pinia').Pinia;
  }
}

export default store(function (_) {
  const pinia = createPinia();
  pinia.use(piniaPluginPersistedstate); // Pinia Plugin added here
  return pinia;
});

And this is what my Pinia store looks like:

src/store/user.ts

import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      user: {
        firstName: 'Mary',
      },
    };
  },
  persist: true, // Note that we are using a persisted state here
  actions: {
    setFirstName(firstName: string) {
      this.user.firstName = firstName;
      console.log('Name set to Pinia store: ', this.user.firstName);
    },
    getFirstName() {
      if (!this.user.firstName) {
        console.log('No name found in store. Setting "John" to Pinia store.');
        this.user.firstName = 'John';
        return this.user.firstName;
      } else {
        console.log('Name fetched from Pinia store: ', this.user.firstName);
        return this.user.firstName;
      }
    },
  },
});

Here is an example front-end page for fetching and setting the firstName:

src/pages/index.vue

<template>
  <div>{{ firstName }}</div>
  <q-form @submit="handleFirstNameSubmit">
    <p>Change First Name</p>
    <q-input v-model="firstNameInput" filled outline />
    <q-btn label="Submit Name to Pinia Store" type="submit" />
  </q-form>
  <q-btn @click="handleFirstNameFetch" label="Fetch Name from Pinia Store" />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useUserStore } from 'src/store/user';
const userStore = useUserStore();
const firstName = ref<string>();
const firstNameInput = ref<string>();
const handleFirstNameSubmit = () => {
  if (firstNameInput.value) {
    userStore.setFirstName(firstNameInput.value);
  }
};
const handleFirstNameFetch = () => {
  firstName.value = userStore.getFirstName();
};
</script>

Up to this point everything works fine.

I can set firstName to the Pinia store, refresh the page, and the new name is still in Pinia.

But when trying to use const userStore = useUserStore(store) inside a boot file like the example below, the persisted state stops working:

src/boot/auth.ts

import { boot } from 'quasar/wrappers';
import { useUserStore } from 'src/store/user';

export default boot(({ store }) => {
  const userStore = useUserStore(store);
  // Do some other authentication stuff, setting initial user store values etc, below here...
});

Any idea what's going on? And how to fix it?

I think this plugin is much cleaner than using the alternate LocalStorage persisted state solution so I would love to get it working with Quasar.

Nuxt configuration is not working for Nuxt2.x (Cannot find module '#app')

Says in documentation that plugin works in Nuxt 2, but example in documentation is not working.

`TS2307: Cannot find module '#app' or its corresponding type declarations.
1 | import { createNuxtPersistedState } from 'pinia-plugin-persistedstate'

2 | import { defineNuxtPlugin, useCookie } from '#app'
| ^^^^^^
3 |
4 | export default defineNuxtPlugin(nuxtApp => {
5 | nuxtApp.$pinia.use(createNuxtPersistedState(useCookie))`

Removing this line and trying to do correct import statements, will lead to errors for useCookie(not found)

Suggestion: Just persist the state when path element (if it has been used) is changed

Hello,

I'm using the paths property with some propertis of the store.
I have a little problem because the the store is persisted when any property of the store is changed, not only when a property of the path is changed.

I think the store must be update the storage when any of the persisted properties has changed, but not other properties.

Thanks,

Plugin not rehydrate state from localStorage

plugin pinia persisted not rehydrate state from localStorage, can you help me please?

companyStore.ts

interface CompanyStore {
  activeCompany: object,
  listCompany: BusinessType[]
}

export const useCompanyStore = defineStore({
  id: 'companyStore',
  state: ():CompanyStore => ({
     activeCompany: {},
     listCompany: []
   }),
  persist: true,
  actions: {
	setActiveCompany(data:BusinessType) {
		this.activeCompany = data
	},
        setListCompany(data:BusinessType[]) {
         this.listCompany = data
        }
     }
  // getters: {
  //   getListCompany: (state) => state.listCompany
  // }
})

main.ts

...
const pinia = createPinia()
pinia.use(piniaPluginPersistedState)

createApp(App)
  .use(pinia)
  .use(router)
  .use(i18n)
  .component('MainLayout', MainLayout)
  .mount('#app')

image
Update: The hydratation is lose when navigate between routes, or only exists in path '/'
Update2: while the state is not called in some way in the route where it will be used, it does not appear and the persistence does not work

Pina subscription should be detached

When the plugin function in index.ts calls $subscribe on the Pinia store, it should pass { detached: true } as a second argument to $subscribe. By default, Pinia state subscriptions are bound to whatever component was active when subscribe was called, which means the subscription will be removed when the component is unmounted. This is not what's wanted in this case.

See here for a description of when to use { detached: true }:
https://pinia.vuejs.org/core-concepts/state.html#subscribing-to-the-state

The fix would be to change the subscribe code to this:

  store.$subscribe((_mutation: unknown, state: unknown) => {
    try {
      const toStore = Array.isArray(paths)
        ? pick(state, paths)
        : state

      storage.setItem(key, JSON.stringify(toStore))
    } catch (_error) {}
  }, { detached: true })

I'll submit a PR with this change.

Unable to persist

// userStore.ts
import {defineStore} from "pinia";
import {IUser} from "../api/type/IUser";
import {ref} from "vue";

export const useUserStore = defineStore(
  "user",
  () => {
    const user = ref<IUser>({
      id: null,
      nickName: null,
      avatarUrl: null,
    });
    const token = ref<string>("");
    const refreshToken = ref<string>("");
    const isLoggedIn = ref<boolean>(false);

    const setUser = (data: IUser) => {
      user.value = data;
    };

    const setToken = (data: string) => {
      token.value = data;
    };

    const setRefreshToken = (data: string) => {
      refreshToken.value = data;
    };

    const setIsLoggedIn = (data: boolean) => {
      isLoggedIn.value = data;
    };
    return {
      user,
      token,
      refreshToken,
      isLoggedIn,
      setUser,
      setToken,
      setRefreshToken,
      setIsLoggedIn,
    };
  }, {
    persist: {
      key: 'user',
      storage: window.localStorage,
      serializer: {
        serialize: JSON.stringify,
        deserialize: JSON.parse,
      },
      beforeRestore: context => {
        console.log('Before hydration...')
      },
      afterRestore: context => {
        console.log('After hydration...')
      },
    }
  }
);

Dependent Versions

specifiers:
  '@vitejs/plugin-vue': ^2.3.0
  autoprefixer: ^10.4.4
  axios: ^0.26.1
  install: ^0.13.0
  naive-ui: ^2.27.0
  nprogress: ^0.2.0
  pinia: ^2.0.0-rc.10
  pinia-plugin-persistedstate: ^1.5.1
  postcss: ^8.4.12
  protobufjs: ^6.11.2
  tailwindcss: ^3.0.23
  typescript: ^4.5.4
  unplugin-vue-components: ^0.18.5
  vite: ^2.9.0
  vue: ^3.2.25
  vue-router: ^4.0.14
  vue-tsc: ^0.29.8

dependencies:
  axios: 0.26.1
  install: 0.13.0
  nprogress: 0.2.0
  pinia: [email protected][email protected]
  pinia-plugin-persistedstate: [email protected]
  vue: 3.2.31
  vue-router: [email protected]

devDependencies:
  '@vitejs/plugin-vue': [email protected][email protected]
  autoprefixer: [email protected]
  naive-ui: [email protected]
  postcss: 8.4.12
  protobufjs: 6.11.2
  tailwindcss: [email protected]
  typescript: 4.6.3
  unplugin-vue-components: [email protected][email protected]
  vite: 2.9.1
  vue-tsc: [email protected]

code:

const loginHandler = async () => {
  const res = await UserService.login(loginModel.value)
  if (res.code === 200) {
    userStore.setToken(res.data.accessToken);
    userStore.setUser(res.data.user);
    userStore.setRefreshToken(res.data.refreshToken);
    userStore.setIsLoggedIn(true);
    message.success('login success');
  } else {
    message.error(res.message);
    loginModel.value.password = '';
  }
};

When I save data to pinia, the plugin does not persist

nuxt3 bulid error

// shell
$ node .output/server/index.mjs
Listening on http://localhost:3000/
TypeError: extender is not a function
    at file:///Volumes/www/vue/.output/server/node_modules/pinia/dist/pinia.mjs:1558:43
    at EffectScope.run (/Volumes/www/vue/.output/server/node_modules/@vue/reactivity/dist/reactivity.cjs.js:27:24)
    at file:///Volumes/www/vue/.output/server/node_modules/pinia/dist/pinia.mjs:1558:33
    at Array.forEach (<anonymous>)
    at createSetupStore (file:///Volumes/www/vue/.output/server/node_modules/pinia/dist/pinia.mjs:1545:14)
    at createOptionsStore (file:///Volumes/www/vue/.output/server/node_modules/pinia/dist/pinia.mjs:1142:13)
    at useStore (file:///Volumes/www/vue/.output/server/node_modules/pinia/dist/pinia.mjs:1622:17)
    at setup (file:///Volumes/www/vue/.output/server/chunks/app/server.mjs:10416:23)
    at _sfc_main.setup (file:///Volumes/www/vue/.output/server/chunks/app/server.mjs:10656:23)
    at callWithErrorHandling (file:///Volumes/www/vue/.output/server/chunks/index.mjs:1957:22)
[Vue warn]: Component  is missing template or render function.

and in Browser:
image

Hydration completed but contains mismatches. 

My environment:

package.json
{
  "private": true,
  "scripts": {
    "dev": "nuxi dev",
    "build": "nuxi build",
    "deploy": "yarn build && yarn start",
    "start": "node .output/server/index.mjs"
  },
  "devDependencies": {
    "naive-ui": "^2.26.0",
    "nuxt-windicss": "^2.2.8",
    "nuxt3": "latest",
    "unplugin-vue-components": "^0.17.21"
  },
  "dependencies": {
    "@pinia/nuxt": "^0.1.8",
    "pinia": "^2.0.11",
    "pinia-plugin-persistedstate": "^1.3.0"
  }
}
nuxt.config.ts
import { defineNuxtConfig } from 'nuxt3'
import Components from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
    build: {
        // fix dev error: Cannot find module 'vueuc'
        transpile: ['vueuc'],
    },
    vite: {
        plugins: [
            Components({
                // Automatically register all components in the `components` directory
                resolvers: [NaiveUiResolver()],
            }),
        ],
        // @ts-expect-error: Missing ssr key
        ssr: {
            noExternal: ['moment', 'naive-ui'],
        },
    },
    buildModules: [
        /**
         * @see https://cn.windicss.org
         */
        'nuxt-windicss',
        /**
         * @see https://pinia.vuejs.org
         */
        '@pinia/nuxt',
    ],
    windicss: {
        analyze: true
    }
})
plugins/pinia-persist.ts
import PiniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.$pinia.use(PiniaPluginPersistedstate)
})
composables/useUser.ts
import { defineStore } from "pinia";

export default defineStore({
    id: 'user',
    state: () => ({
        a: 1
    }),
    getters: {

    },
    actions: {
    },
    persist: {
        storage: {
            getItem: (key) => { return useCookie(key, { encode: x => x, decode: x => x }).value },
            setItem: (key, value) => { useCookie(key, { encode: x => x, decode: x => x }).value = value },
        },
    },
})

How to use with dexie?

I should use dexie for dexie's large capacity but i can't adjust dexie in this library.
I got the error like that

the call to a function does not correspond to any overload of ...

This is my code.
This library not support dexie?
I totally like this library... please support!

import { defineStore } from "pinia";
import db from "@/assets/js/db";
export default defineStore("app", {
  state: () => ({
    isModal: false,
    isSelectOpen: false,
  }),
  getters: {},
  actions: {},
  persist: {
    key: "storekey",
    storage: db,
    paths: ["nested.data"],
    overwrite: true,
    beforeRestore: (context) => {
      console.log("Before hydration...");
    },
    afterRestore: (context) => {
      console.log("After hydration...");
    },
  },
});

More right configure in example

Thank you for your very nice library firstly.

I have some problems about usage, can you share more right configure about presist?
Just {presist: true} in example, maybe somebody want to custom this option, and debug example project in local env.

Finally, thanks for the detailed documentation

String with semicolon doesn't persist

I'm using pinia-plugin-persistedstate with Nuxt3 and can't seem to persist strings with semicolons in them. The code below illustrates the issue. When I remove the semicolon from the line this.test = "foo; bar" everything works as expected, however, when the semicolon is present the state doesn't seem to get persisted. Is this a bug or an error with my use of the package? Any assistance would be greatly appreciated.

import { defineStore } from "pinia";

export const useTestStore = defineStore("test", {
  state: () => {
    return {
      test: null,
    };
  },
  actions: {
    doTest() {
      console.log("PERSISTED", this.test);
      this.test = "foo; bar";
      console.log("FETCHED", this.test);
    },
  },
  persist: true,
});

how to use in setup

image
i use this way to define store,but i don't know how to use plugin, can someone help me, thanks!

When there is object type data in the state, the persistence fails

Hi @prazdevs , I use Nuxt3 rc-1 & pinia & pinia-plugin-presistedstate in my project.
I found that when the fields in state has least one object type (multiple layers), the persistence fails.
for example: state.cartInfo is a Object type value.
image

I don't know if this is caused by your plugin or usecookie in Nuxt3.
besides, Could you give more examples on using localStorage in Nuxt3, when I make the value of config key "storage" as window.localStorage or localStorage, it throw a undefined error

Usage with Nuxt3 (SSR)

Hello! Thanks for great package. My problem:

  1. Nuxt 3, vue 3, pinia 2.0
  2. Create plugin, code:
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
import {NuxtApp} from 'nuxt3';

export default function ({$pinia, ssrContext}: NuxtApp) {
  $pinia.use(piniaPluginPersistedstate);
}
  1. Then I create build (ssr enabled) and then start server, I get this error:
extender is not a function
  at file://./server/node_modules/pinia/dist/pinia.mjs:1556:43
  1. This block of code in pinia.mjs:
// apply all plugins
pinia._p.forEach((extender) => {
  assign(store, scope.run(() => extender({
      store,
      app: pinia._a,
      pinia,
      options: optionsForPlugin,
  })));
})

How should i use package correctly with nuxt3 ssr?

How to solve the problem that "persist "does not exist?

Environment: vue3.2.25+pinia2.0.13+vite2.9.7+ts4.5.7

export const useUserStore = defineStore({ id: 'user', state: () => { return {} }, persist: true // 'persist' is not in type 'DefineStoreOptions<"user", {}, {}, {}>" })
A parameter of type "{ id: "user"; state: () => {}; persist: boolean; }" cannot be assigned to a parameter of type "DefineStoreOptions<"user", {}, {}, {}>".
Object literals can specify only known properties and 'persist' is not in type 'DefineStoreOptions<"user", {}, {}, {}>"

Thanks for any reply

pinia.use(...) giving context is undefined

Uncaught (in promise) TypeError: context is undefined
src_default index.mjs:4
install pinia.ts:5
viteApp main.ts:13
viteApp main.ts:13
createApp$1 index.mjs:51
ViteSSG index.mjs:77

I can't recreate the "References do not persist" issue

I am trying to recreate the References do not persist issue to better understand it.

So I made this real world scenario with the object stored in state and then assigned to a const.

src/store/test.ts

import { defineStore } from 'pinia';

interface Test {
  1: string;
  2: string;
}

export const useTestStore = defineStore('test', {
  state: () => {
    return {
      test: {} as Test,
    };
  },
  actions: {
    setTest(test: Test) {
      this.test = test;
    },
  },
  persist: true,
});

src/components/SomeComponent.vue

<template>
  <div>Test Component</div>
</template>

<script setup lang="ts">
import { useTestStore } from 'src/store/test';
const testStore = useTestStore();
testStore.setTest({
  1: 'one',
  2: 'two',
});
const b = testStore.test;
console.log(testStore.test === b); // always returns true, even after page refresh
</script>

From the issue description, I thought the console.log() would return false after page refresh. But it always returns true. So it seems the issue is not actually a problem at all?

So I can understand this better, are you able to give a code example of the "References do not persist" issue when using the Pinia store? The code example in the docs doesn't involve the Pinia store at all so I'm not sure how it applies to this Pinia plugin.

[core] Persisted state doesn't update when calling this.$reset() and then setting state values

Minimal example:

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  persist: true,
  actions: {
    // If this function is not async with await on $reset, the localstorage doesn't update (even though pinia does update)
    // If F5 is pressed after setCounter has been called, counter will go back to previous state instead of 100
    setCounter100() {
      this.$reset();
      this.counter = 100
    },
  },
})

How can i use Cookies options?

I want to set maxAge for the persisted state using Pinia in Nuxt 3. However, TypeScript keeps telling me that this is not assignable.

ảnh

Date objects are converted to strings

In the following scenario the Date() object is converted to a string after page refresh:

state: () => {
  items: []
}

actions: {
  addItem(data) {
    const newItem = data
    newItem.createdDt = new Date()
    this.items.push(newItem)
  }
}

When I add the item and retrieve it immediately, it is a Date object. However, after refreshing the page, when the store is restored from local storage items[0].createdDt is a string.

packaging failed.

Hello, I used your project in the vue3 project, but the packaging failed.
Terminal say 'Cannot find module 'nuxt3/dist/app/composables/cookie' or its cor
3 import { CookieOptions, CookieRef } from 'nuxt3/dist/app/composables/cookie';'
I found that this project didn't delete' CreateNuxtPersistent State' when I didn't use it.So I deleted it manually.Then my project is packed normally.

How should I do with encryption libraries but choosing sessionStorage?

I mean: How do I tell the storage to use sessionStorage and keep the three encryption methods? Can you help me with this please? Thanks in advance.

import { store } from 'quasar/wrappers'
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import SecureLS from "secure-ls";
const ls = new SecureLS({ isCompression: false });

/*

  • If not building with SSR mode, you can
  • directly export the Store instantiation;
  • The function below can be async too; either use
  • async/await or return a Promise which resolves
  • with the Store instance.
    */

export default store((/* { ssrContext } */) => {
const pinia = createPinia()

// You can add Pinia plugins here
pinia.use(createPersistedState({
storage: {
getItem: (key) => ls.get(key),
setItem: (key, value) => ls.set(key, value),
removeItem: (key) => ls.remove(key)
}
}))

return pinia
})

[core] support conditional storage

Sometimes we need to use a path to determine whether another path needs to be persisted, so I suggest to expanding the options.paths

type CheckStateProp = (store: PiniaPluginContext['store']) => boolean
type PropPath = string | [string, CheckStateProp]


...
// when use
paths: ['a', ['b', (store) => store.a === true]]

if a is true, b will persisted, otherwise not persisted b

SecureLS

Cant make it work with SecureLS.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.