Home > OS >  Firebase -- Uncaught TypeError: database.ref is not a function
Firebase -- Uncaught TypeError: database.ref is not a function

Time:10-21

I apologize if this is not a good question (I am fairly new to Firebase and programming in JavaScript).

I have been trying to get a relatively simple program up and running. Specifically, when I run my code, I would like a 'Start' button to appear. Once a user clicks on this button, it will increment the number of players by one and update the playerCount in my Firebase Realtime Database accordingly.

I noticed that when I run this program, I get an error: "Uncaught TypeError: database.ref is not a function"

Here is my index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script defer type="module" src="https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"></script>
    <script defer type="module" src="https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js"></script>
    <script defer type="module" src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>
    <script defer type="module" src="game.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

</body>
</html>

And here is my game.js code:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
import { getDatabase } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js';

// Your web app's Firebase configuration

// For Firebase JS SDK v7.20.0 and later, measurementId is optional

const firebaseConfig = {

    apiKey: "apiKey information",

    authDomain: "authDomain information",

    databaseURL: "databaseURL information",

    projectId: "projectId information",

    storageBucket: "storageBucket information",

    messagingSenderId: "messagingSenderId information",

    appId: "appId information",

    measurementId: "measurementId information"

};

const app = initializeApp(firebaseConfig);
// Store Firestore database in db
const database = getDatabase(app);

var player_num = 0;

// Display Start Button and increment player count
let button = document.createElement('button');
button.innerHTML = "Start";
button.onclick = function () {
    player_num  ;
    database.ref('/').update({
        playerCount: player_num
    });
    button.style.display = "none";
};
document.body.appendChild(button);

I suspect that either I may not set up the browser modules correctly, but I am not entirely sure. Any help would be much appreciated!

CodePudding user response:

database.ref('/') this doesn't seem right.

Normally you would look for a root node with a name like database.ref('game/').

  • Related