GithubHelp home page GithubHelp logo

Comments (6)

throrin19 avatar throrin19 commented on May 29, 2024 1

@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.

prazdevs avatar prazdevs commented on May 29, 2024

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.

AndreiSoroka avatar AndreiSoroka commented on May 29, 2024

@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.

N0tExisting avatar N0tExisting commented on May 29, 2024

You can use afterRestore as the setup hook

from pinia-plugin-persistedstate.

IlyaSemenov avatar IlyaSemenov commented on May 29, 2024

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 avatar AndreiSoroka commented on May 29, 2024

@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)

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.