Comments (6)
@AndreiSoroka you have this plugin for pinia to make the sync between tabs. I don't know if we can use it with persistentstate plugin : https://github.com/wobsoriano/pinia-shared-state
from pinia-plugin-persistedstate.
Hi, I think this is out of the scope of the package, but I can give you a solution for this.
You can decalre your store state using setup function and the createGlobalState
or createSharedComposable
from VueUse, I think it fits perfectly what you're looking for!
https://vueuse.org/shared/createglobalstate/
from pinia-plugin-persistedstate.
@prazdevs thanks for your answer.
Maybe is it possible add setup
? like this code:
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
nested: {
data: 'nested pinia',
},
}
},
persist: {
key: 'storekey',
setup(context, presisData) {
// ... here I can add listeners when tab is opened
},
storage: window.sessionStorage,
paths: ['nested.data'],
beforeRestore: (context) => {
console.log('Before hydration...')
},
afterRestore: (context) => {
console.log('After hydration...')
},
},
})
How does it help me? I can add listeners when the tab is opened like this
document.addEventListener('visibilitychange', () => { // when tab is active then need restore from other tab
if (document.hidden) {
return;
}
storeAuth.$state = storage.genericStore(
storeAuth.$state,
isAuthState,
{ isLoading: false },
);
});
P.s.
My temporary resolve:
Storage class (only for function genericStore)
class Storage {
#name = '';
constructor(name: string) {
this.#name = name;
}
getPersistedState() {
try {
const data = localStorage.getItem(this.#name);
if (!data) {
return null;
}
return JSON.parse(data);
} catch (_) {
return null;
}
}
setPersistedState(data: object) {
try {
localStorage.setItem(this.#name, JSON.stringify(data));
} catch (e) {
console.log(e);
}
}
genericStore<Store>(
store: Store,
validator: (arg: unknown) => arg is Store,
forceData: Partial<Store> = {},
): Store {
const persistedState = this.getPersistedState();
return {
...store,
...(persistedState && validator(persistedState) ? persistedState : {}),
...forceData,
};
}
}
in pinia store:
// ...
// connect storage
const storage = new Storage('store-auth');
const useStoreAuth = defineStore('auth', {
state: (): AuthState => storage.genericStore<AuthState>( // get data from localstorage or use default (with types)
{
token: null,
tokenExpiration: null,
refresh: null,
refreshExpiration: null,
errorMessage: '',
isLoading: false,
tokenData: null,
},
isAuthState,
{
isLoading: false, // just reset part of state
},
)
/// .....
});
const storeAuth = useStoreAuth();
storeAuth.$subscribe((mutation, state) => { // save each mutation
if (mutation.type === 'patch object') {
storage.setPersistedState(state);
}
});
document.addEventListener('visibilitychange', () => { // when tab is active then need restore from other tab
if (document.hidden) {
return;
}
storeAuth.$state = storage.genericStore(
storeAuth.$state,
isAuthState,
{ isLoading: false },
);
});
export default useStoreAuth;
from pinia-plugin-persistedstate.
You can use afterRestore
as the setup hook
from pinia-plugin-persistedstate.
pinia-shared-state works, put this to plugins/1-pinia-shared-state.ts
:
import { PiniaSharedState } from "pinia-shared-state"
export default defineNuxtPlugin(() => {
const pinia = useNuxtApp().$pinia
pinia.use(PiniaSharedState({}))
})
from pinia-plugin-persistedstate.
@AndreiSoroka you have this plugin for pinia to make the sync between tabs. I don't know if we can use it with persistentstate plugin : https://github.com/wobsoriano/pinia-shared-state
I use https://vueuse.org/core/useStorage/ where no need to use MF (Module Federation). With MF vueuse/vueuse#2916 (comment)
from pinia-plugin-persistedstate.
Related Issues (20)
- Having interval inside a persistent store breaks persisting
- [pinia-plugin-persistedstate] Error: [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin HOT 2
- In the cookie store defineNuxtRouteMiddleware method was used in nuxt3 unable to get to the store of value HOT 3
- Critical security vulnerability? HOT 6
- nuxt bug Cannot read properties of undefined (reading 'sessionStorage') HOT 1
- Automatically set `Vary: Cookie` response header in Nuxt SSR
- pinia.use(piniaPersist) in a separate file, causing local storage to fail HOT 2
- Missing "./package.json" export HOT 1
- Not effective when working with vee-validate
- Global `cookieOptions` are not applied in Nuxt 3 HOT 1
- Type safe persist paths HOT 2
- Store not hydrated from cookies when used with `@nuxtjs/i18n` and `routeRules`
- Using store outside setup(), state persistence is not possible HOT 1
- The type of map print in console.log (typeof this.userMap) is object HOT 1
- Persist for "composition api" style HOT 1
- 配置 storage: persistedState.sessionStorage 会导致 v-bind 失效
- Vue: Argument of type HOT 2
- when to persist and when to recover
- How to Securely store an object in local storage without storing It as plain object? HOT 5
- not able to use persistence in plugins created from user modules HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pinia-plugin-persistedstate.