Firebase Database Returns Error "database is not a function"

Hello everyone,

I am trying to save to my Firebase database and I am using import using the URLs in JavaScript. It keeps returning database is not a function in the console. Please help me figure this out.

Error In Console:

database is not a function

My Code: (JavaScript)

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

const firebaseApp = initializeApp({
    apiKey: "~",
    authDomain: "~",
    projectId: "~",
    storageBucket: "~",
    messagingSenderId: "~",
    appId: "~",
    measurementId: "~"
});

const database = getDatabase(firebaseApp);

database().ref("lol").set(true);

My Code: (HTML)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>~</title>

    <link rel="stylesheet" href="/style.css">

    <script type="module" src="/script.js" defer></script>
</head>

<body>

</body>

</html>

Thank you!

Hi TikoGrant,

I don’t recognise your syntax database().ref()...

I looked at the docs: https://firebase.google.com/docs/database/web/read-and-write#write_data

And it suggests a syntax like this, using a reference to the database object like you have:

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

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}
1 Like

Thank you so much. It is working now. You’re the best. :blush:

I just noticed a problem. Since I imported the modules and all the firebase stuff. Other functions don’t work. :frowning:

Thanks.

I have 1 more problem. Sorry for all the problems lol. How do I read data in firebase now?

Hi, I don’t know if you figured it out already, but the page I linked to earlier has examples for reading data too, if you scroll around a bit. I’m not a Firebase user really, sorry!

Thanks, I found it.

1 Like