Home > Software engineering >  How to read/retrieve data from Firebase using Javascript
How to read/retrieve data from Firebase using Javascript

Time:12-19

I am trying to get my datas from firebase with console log but i am getting an error. The error is: image This is my database: https://i.stack.imgur.com/A1zYm.png

<script type="module">
      import {
        initializeApp
      } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
      import {
        getDatabase,
        set,
        ref,
        update
      } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
      import {
        getAuth,
        createUserWithEmailAndPassword,
        signInWithEmailAndPassword,
        onAuthStateChanged,
        signOut
      } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
      const firebaseConfig = {
        apiKey: ,
        authDomain: ,
        databaseURL: ,
        projectId: ,
        storageBucket: ,
        messagingSenderId: ,
        appId: ,
        measurementId:
      };
      const app = initializeApp(firebaseConfig);
      const db = getDatabase(app);
      const auth = getAuth();
      const firebaseRef = firebase.database().ref("Users");
      firebaseRef.once("value", function(snapshot) {
        snapshot.forEach(function(element) {
          console.log(element);
        })
      });
    </script>

CodePudding user response:

You're trying to use the old v8 syntax with Firebase SDK 9, which won't work. You'll either have to use the new modular syntax, or import the older SDKs or the compatibility versions on v9.

In v9 syntax, getting a reference to and reading a value from the database is done with:

import { getDatabase, ref, get } from "firebase/database";

...

const database = getDatabase();

const firebaseRef = ref(database, "Users");
get(firebaseRef, function(snapshot) {
  snapshot.forEach(function(element) {
    console.log(element);
  })
});

For more examples, see the Web version 9 (modular) tabs in the documentation I linked above, and the upgrade guide specifically the section on upgrading with the compat libraries.

  • Related