'Ionic-storage with vue

I'm building an application using Ionic Framework v5 with Vue 3.0.0.

I use Vuex store to store global app informations, such as the user login token.

// file src\store.ts
export const store = createStore({
    state(){
      return { 
        loginToken;
      }
    },
    mutations: {
      updateLoginToken(state: any, token: string){
        state.loginToken = token;
      }
    },
    getters: {
      token(state: any){
        return state.loginToken;
      }
    }
})

I also need that this token is saved when the app is closed or refreshed, so i need to store it in some kind of local storage.

Official documentation suggest to use @ionic/storage to have access to a storage engines on multiple platforms.

To initialize the store i need to execute this code:

import { Storage } from '@ionic/storage';

const storage = new Storage();
await storage.create();

I'm pretty new to all this and i can't find where to place this code to initialize the storage, and also how can i then access to the storage object inside vuex store, to execute storage.set(...) and storage.get(...)?



Solution 1:[1]

What i've done to make this all to work:

I've created a plugin file called Storage.ts that creates the plugin instance and adds it to app global properties:

import { Storage } from '@ionic/storage'

export default async function storageFactory(wsBaseUrl: string) {

  const storage = new Storage();
  // create storage
  const storageInstance = await storage.create();

  // my custom stuff here ...

  // in the end, return the plugin installer
  return {
    install(app: any){
      app.config.globalProperties.$ionicStorage = storageInstance;
      // special copy for vuex storage
      app.config.globalProperties.$store.$ionicStorage = storageInstance; 
    }
  }
}

Then in the main.ts i've added my custom plugin to the main app:

import storageFactory from '@/plugins/Storage';

// create storage plugin 
const storagePlugin = await storageFactory(config.wsBaseUrl);

// create app
const app = createApp(App)
  // ... other stuff here
  .use(storagePlugin)

// mount when router is ready
router.isReady().then(() => {
  app.mount('#app');
});

Then, anywhere in other app's files i use the storage like this:

// set new key
await (this as any).$ionicStorage.set('token', token );
// remove the key
await (this as any).$ionicStorage.remove('token');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman