EddyVerbruggen / nativescript-plugin-firebase

:fire: NativeScript plugin for Firebase
https://firebase.google.com
MIT License
1.01k stars 446 forks source link

Please run firebase.init before firebase.firestore.collection() #1588

Closed hankster76 closed 4 years ago

hankster76 commented 4 years ago

I am creating a new app using the firebase plugin. i placed the .init code from the example in app.js

firebase.init({ // Optionally pass in properties for database, authentication and cloud messaging, // see their respective docs. }).then( function () { console.log("firebase.init done"); }, function (error) { console.log("firebase.init error: " + error); } );

and the code to connect in a mounted function inside home.vue

    mounted: function() {
      console.log("inside Mounted Function");
      miscCollection.get({ source: "server" }).then(querySnapshot => {
        querySnapshot.forEach(doc => {
          this.misc = JSON.stringify(doc.data());
          console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
        });
      });

    }

this worked just great for a while, then for some reason i started getting an error that said:

Please run firebase.init() before firebase.firestore.collection()

it seems as if I need to wait for firebase.init() to officially end before i do anything else. none of the examples i looked at don't seem to have any concern over this.

can you suggest a way that i can get past this issue?

I appreciate any advice and help!

Dan Mitchell dmitchel@progress.com

manojdcoder commented 4 years ago

Init returns a promise, so you will have wait for it to be resolved completely. Since you are using Vue, you could use an event bus or mutations to handle firebase initialisation status.

You may also try loaded / navigation events of your Page instead of mounted, but waiting for the promise to be resolved is still the best option.

hankster76 commented 4 years ago

thanks for the response. i'm a fairly new developer using {N} and Vue. can you show an example of how it would implement (if you can? understand if not)

manojdcoder commented 4 years ago

I'm not much of Vue guy, but here is what I imagine you would do.

Create a file named event-bus.js

import Vue from 'vue';
export const EventBus = new Vue();

In your init call,

import { EventBus } from './event-bus.js';

firebase.init({ ... }).then(
   function () {
     EventBus.$emit("firebase-init");
   },
  function (error) {
    console.log("firebase.init error: " + error);
  }
);

Before accessing collection,

if (firebase.initialized) {
   // call your function to read collection
} else {
  EventBus.$once("firebase-init", ()=> {
    // call your function to read collection
 });
}

Or simply give a try for loaded event on Page element instead of component mount,

<Page @loaded="onLoaded"
....
methods: {
  onLoaded() {
   ....
 }
}
hankster76 commented 4 years ago

that worked correctly. Thank you for your help!