'Restoring Vue state (vuex) when reopening app

I'm porting an existing Vue2 application to iOS and Android via the CapacitorJS plugin and currently the only hurdle I am facing is getting the application state to persist when closed and resumed.

Currently, in the web, I am using this method to fetch user data if needed

firebase.auth().onAuthStateChanged((user) => {
  const authAction = isNil(user) ? 'logout' : 'login'
  store.dispatch(`auth/${authAction}`, user)
})

however, from what I understand, Firebase stores the auth info differently in browser than native, so my native apps won't detect an actual auth state change, and Native apps do not use localStorage so my persisted Vuex state is not enough and I will need to use the Capacitor Storage API.

I've attempted to use the Capacitor listener, but honestly I think I just don't understand how to properly use the Capacitor API because I have had no luck with this.

For example, attempted to test just forcing a user to stay logged in like so in my App.vue

mounted() {
    App.addListener('appStateChange', ({ isActive }) => {
        if (Capacitor.isNativePlatform()) {
            if (!isActive && this.userId) {
                Storage.set({
                    key: 'firebaseUser',
                    value: JSON.stringify({
                        id: this.userId,
                    }),
                })
            } else if (isActive) {
                const ret = Storage.get({ key: 'firebaseUser' })
                const firebaseUser = JSON.parse(ret.value)
                this.login(firebaseUser)
            }
        }
    })
},

but obviously no luck.

Would anyone be able to fill in the gaps of my understanding of this or provide some better insight? Would I be better off to use the Capacitor Storage API and make read/write state parallel to Vuex? (If so, is there a clean way to do that?)



Solution 1:[1]

There should be two ways to solve your problem:

  • You can use a plugin (for example @capacitor-firebase/authentication). This persists the state for you and fires onAuthStateChanged on startup.
  • You can try to set persistence to indexedDBLocalPersistence when initializing Firebase Authentication:
initializeAuth(firebaseApp, {
  persistence: indexedDBLocalPersistence
});

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 RGe