pizzalawl
pizzalawl

Reputation: 43

Trying to put data in database but get error "firebase is not defined"

I'm trying to make a basic login/signup system with firebase. So far I've been able to fix all the other bugs. The program first creates a user with Firebase Authentication then puts the user data in the Firebase Database. I've managed to get the Authentication working but the database part just makes firebase spit out, "firebase is not defined".

Here's the code:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";

const firebaseConfig = {
    apiKey: "AIzaSyCQjuF9A4Km_M7Eo5gnd1B6nmDRRYSle2c",
    authDomain: "badge-world.firebaseapp.com",
    projectId: "badge-world",
    storageBucket: "badge-world.appspot.com",
    messagingSenderId: "186421361260",
    appId: "1:186421361260:web:852bcaa237f86a76b1f649"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
document.getElementById ("signup-button").addEventListener("click", register);
document.getElementById ("login-button").addEventListener("click", login);


function register() {
    let email = document.getElementById('email').value
    let password = document.getElementById('password').value
    let username = document.getElementById('username').value

    if (validate_email(email) == false || validate_password(password) == false) {
        alert("Incorrect Fields. Remember password has to have more than 6 characters and there must be a valid email.")
    }

    if(validate_field(username) == false) {
        alert("Username missing")
    }

    createUserWithEmailAndPassword(auth, email, password)
    .then(function (){
        var user = auth.currentUser

        var rootRef = firebase.database().ref();

        var user_data = {
            email : email,
            password : password,
            username: username,
            last_login : Date.now
        }

        rootRef.child('users/' + user.uid).set(user_data)

        alert("User Created!")
    })
    .catch(function(error) {
        var error_code = error.code
        var error_message = error.message

        alert(error_message)
    })

}

function login() {

}

// Validate Functions
function validate_email(email) {
  let expression = /^[^@]+@\w+(\.\w+)+\w$/
  if (expression.test(email) == true) {
    // Email is good
    return true
  } else {
    // Email is not good
    return false
  }
}

function validate_password(password) {
  // Firebase only accepts lengths greater than 6
  if (password < 6) {
    return false
  } else {
    return true
  }
}

function validate_field(field) {
  if (field == null) {
    return false
  }

  if (field.length <= 0) {
    return false
  } else {
    return true
  }
}

and here's the database part that seems to be causing the issue:

.then(function (){
        var user = auth.currentUser

        var rootRef = firebase.database().ref();

        var user_data = {
            email : email,
            password : password,
            username: username,
            last_login : Date.now
        }

        rootRef.child('users/' + user.uid).set(user_data)

        alert("User Created!")
    })
    .catch(function(error) {
        var error_code = error.code
        var error_message = error.message

        alert(error_message)
    })

Any help is appreciated!

Upvotes: 0

Views: 28

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

You are using Firebase Modular SDK that uses a functional syntax and not the firebase. namespaced one. The problem is this line:

var rootRef = firebase.database().ref();

There is a top level function ref() to get a DatabaseReference now. Try refactoring the code as shown below:

import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";

// declared while initializing
const database = getDatabase(app)

set(ref(database, 'users/' + user.uid), user_data)
  .then(() => {
    console.log("data added")
  })
  .catch((e) => console.log(e))

The documentation has examples of both the syntaxes so make sure you are referring to modular tab.

Upvotes: 1

Related Questions