Search code examples
javascriptfirebasevue.jsvuefire

How can you read a Firebase Data in VueJS?


I followed a tutorial for Firebase, Vue.js and VueFire, but I'm having so much trouble. The database is Realtime Database, not Firestore, and all I'm getting returned when I try to look at a collection of data is either "undefined" or an object with a bunch of junk I can't understand (when I expected json). The database rules are configured to be read. What am I doing wrong?

import Firebase from "firebase";

// firebase init goes here
let config = {
  apiKey: "removed",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: ""
};

let app = Firebase.initializeApp(config);
let db = app.database();
let postsRef = db.ref("posts");

//postsRef returns undefined. Why?!?!?

or there's this... what am I supposed to do with this:

Reference {repo: Repo, path: Path, queryParams_: QueryParams, orderByCalled_: false}
database: Database
key: "posts"
orderByCalled_: false
parent: Reference
path: Path {pieces_: Array(1), pieceNum_: 0}
queryParams_: QueryParams {limitSet_: false, startSet_: false, startNameSet_: false, endSet_: false, endNameSet_: false, …}
ref: Reference
repo: Repo {repoInfo_: RepoInfo, app: FirebaseAppImpl, dataUpdateCount: 0, statsListener_: null, eventQueue_: EventQueue, …}
root: Reference
__proto__: Query

Solution

  • That postsRef returns a Reference to the Query's location. You have methods on that ref to extract the right data.

    Check the firebase api, there are a few examples there: https://firebase.google.com/docs/reference/js/firebase.database.Reference#key

    You might want to try postsRef.toJSON() to get the JSON object you need.