skip to Main Content

i have this issue of ‘firebase is not defined’ when i try to read and display data from the relatime database.
I am using firebase to host a simple site in which you input 4 values and receive a score back, everything is scored in the database. i then want to display the highest 10 scores from the database, and im having trouble doing that.
Ive seen lot of people having this issue, but their resolutions are not working for me

Here is my code

                   function displayTopScores() {
          // Reference to the scores in the database
          var scoresRef = firebase.database().ref("scores");
          // Retrieve the top 10 scores
          scoresRef.orderByChild("Score").limitToFirst(10).on("value", function(snapshot) {
            var scores = snapshot.val();
            // Array to store the top 10 scores
            var topScores = [];
            // Add the scores to the array
            for (var score in scores) {
              topScores.push(scores[score]);
            }
            // Sort the scores in descending order
            topScores.sort(function(a, b) {
              return b.Score - a.Score;
            });
            // Create a table to display the scores
            var table = document.createElement("table");
            table.setAttribute("class", "table table-striped");
            // Add a header row to the table
            var headerRow = table.insertRow(-1);
            var nameHeaderCell = headerRow.insertCell(-1);
            nameHeaderCell.innerHTML = "Name";
            var scoreHeaderCell = headerRow.insertCell(-1);
            scoreHeaderCell.innerHTML = "Score";
            // Add a row for each score
            for (var i = 0; i < topScores.length; i++) {
              var row = table.insertRow(-1);
              var nameCell = row.insertCell(-1);
              nameCell.innerHTML = topScores[i].Name;
              var scoreCell = row.insertCell(-1);
              scoreCell.innerHTML = topScores[i].Score;
            }
            // Add the table to the HTML page
            var scoresContainer = document.querySelector("#scores-container");
            scoresContainer.innerHTML = "";
            scoresContainer.appendChild(table);
          });
        }
                  const dbRef = ref(getDatabase());
          get(child(dbRef, `scores/Scores`)).then((snapshot) => {
            if (snapshot.exists()) {
              console.log(snapshot.val());
            } else {
              console.log("No data available");
            }
          }).catch((error) => {
            console.error(error);
          });

i have imported (i think) all the right things for this to happen, but i am clearly doing some mistake i have not figured out.
here is what i import:

<script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries
      
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
          apiKey: "---",
          authDomain: "---",
          databaseURL: "---",
          projectId: "---",
          storageBucket: "---",
          messagingSenderId: "---",
          appId: "---",
          measurementId: "---"
        };
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);

        import {getDatabase, set, get, update, remove, ref, child}
        from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

        const database = getDatabase();

I’ve read the documentation on how to import the database and app function, looked at other people with the same issue, tried to ask openAI but with no luck.
tried using different ways of creating a reference and read the data.

2

Answers


  1. Chosen as BEST ANSWER
    function displayTopScores() {
            const dbRef = ref(getDatabase());
            get(child(dbRef, `scores/`)).then((snapshot) => {
              if (snapshot.exists()) {
                console.log(snapshot.val());
                document.getElementById("scores-list").innerHTML = console.log(snapshot.val());
              } else {
                console.log("No data available");
              }
            }).catch((error) => {
              console.error(error);
            });
          }
    

    its not complete solution cause i still cant show in my site the values from the database, but this seems to fix the issue at least in part, now i see the database getting read from the chrome dev tool


  2. You need to pass the app variable as a parameter to getDatabase() it should be getDatabase(app)

    Here is the official code from the firebase documentation:

    import { initializeApp } from "firebase/app";
    import { getDatabase } from "firebase/database";
    
    const firebaseConfig = {
      // ...
      databaseURL: "https://DATABASE_NAME.firebaseio.com",
    };
    
    const app = initializeApp(firebaseConfig);
    
    const database = getDatabase(app);
    

    You can follow further examples from the documentation here: https://firebase.google.com/docs/database/web/start#web-version-9

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