skip to Main Content

Setup

I have a Vue3 + Firebase project.
In its main.ts i am exporting an object called userInfo like this:

export var userInfo :any = {}

Don’t mind the :any, it is to fix Typescripts *some-property* does note exist on type Object.

This object is set by a hook, also inside main.ts that runs when a user is authenticated as follows:

auth.onAuthStateChanged(async () => {
    if(!auth.currentUser) return

    userInfo = await getUserInfo()
})

Now of course, the object is only filled when the onAuthStateChanged hook fires, which is after imports are handled in my .vue files.

Problem

When importing my ´userInfo´ in some .vue file with import {userInfo} from '@/main'
the file of course imports the still empty object.
Sometime after the onAuthStateChanged hook fires and fills the object.

The component however does not refresh the import, meaning i do not have the data that i need inside my .vue file.

Question

I would like the gathering of my userInfo centralized and then just import it into my .vue components instead of manually gathering it everytime i need to use it.

How do i work around this problem of the object being filled after imports are handled?

2

Answers


  1. You can create a mutation using vuex. So all child children and parent parents can interact from anywhere
    example : https://jasonwatmore.com/post/2018/07/14/vue-vuex-user-registration-and-login-tutorial-example

    Moreover :

    export async function getAuthUserID(): Promise<string | undefined> {
      return await new Promise( (resolve, reject) => {
        firebase.auth().onIdTokenChanged(async (user) => {
          if (!user) {
            resolve(undefined);
          } else {
            resolve(user.uid);
          }
    })
      }).then((uid: string | undefined)=>uid).catch(function(e) {
        throw (e);
      });
    }
    Login or Signup to reply.
  2. Other comments and answers are suggesting to use a store and it should be what you are searching for in your project. As you are using Vue3 and Typescript, I would recommend using Pinia which is the current up to date store manager for recent Vue applications and not VueX which is the older store manager.

    You can find really good examples in the documentation. I personally used Pinia in a similar fashion in a personal project, maybe this can help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search