Sy3d
Sy3d

Reputation: 269

How to mount quasar app to dom after firebase connection is initialized?

Hi how do I initialize my quasar app once after I have established a connection to firebase. I need to do this because my route guards checks whether a user is logged in, but if a user refreshes this causes firebase to check whether a current user exists but since it's a async operation it initially returns null. I have previously achieved this using vue where I have done this in my main.js file, but I'm unsure how to do this is quasar boot file.

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './assets/main.css'

import { authService } from './firebase/config'

let app

authService.onAuthStateChanged(() => {
  if(!app){
    app = createApp(App).use(router).mount('#app')
  }
})

Here inside main.js standard vue app, we wait for Firebase Auth to initialize and only after .onAuthStateChanged() method fires, we create our Vue App.

In an quasar app there is no main.js but instead boot files which run some code before main app starts.

Below is what a standard boot files looks like but I am unsure how to convert my main.js to a executable boot file, seems like some properties are missing like mount, createApp & use.

// import something here

// "async" is optional!
// remove it if you don't need it
export default async ({ /* app, router, store */ }) => {
  // something to do
}

Upvotes: 0

Views: 1911

Answers (2)

Sy3d
Sy3d

Reputation: 269

This got it working.

export default async ({ app, router, store }) => {
    return new Promise(resolve => {
        const unsubscribe = authService.onAuthStateChanged(() => {
            resolve()
            unsubscribe()
        })
    })
}

Here is also a useful article on quasar boot flow https://quasar.dev/quasar-cli/boot-files#quasar-app-flow

Upvotes: 1

Dharmaraj
Dharmaraj

Reputation: 50850

Ideally you create a boot file for initializing Firebase in a Quasar project.

Boot files fulfill one special purpose: they run code before the App’s Vue root component is instantiated while giving you access to certain variables, which is required if you need to initialize a library, interfere with Vue Router, inject Vue prototype or inject the root instance of the Vue app.

Create a boot file using the following command:

quasar new boot firebase

This will create a boot file /src/boot/firebase.js

Install Firebase using npm (or yarn) and then add the following code in your boot file:

import firebase from 'firebase/app';
import 'firebase/auth';

const firebaseConfig = {...};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

export const auth = firebase.auth();

As mentioned earlier, boot file runs before Vue component is instantiated. Now you can access this instance of Firebase Auth in any component you want.

import {auth} from "@/boot/firebase"

auth.onAuthStateChanged((user) => {
  //...
})

Upvotes: 1

Related Questions