I keep getting the error firebase.database is not a function

Viewed 4333

I'm trying to link my contact form in a portfolio website to firebase and keep getting (firebase.database is not a function) in my console

This is for the web, using pure javascript

var firebaseConfig = {
  apiKey: "AIzaSyCzX3r8CFw84WSBuCSXR1fWM_hDrwtGMSs",
  authDomain: "portfolio-4c243.firebaseapp.com",
  databaseURL: "https://portfolio-4c243.firebaseio.com",
  projectId: "portfolio-4c243",
  storageBucket: "",
  messagingSenderId: "745737502175",
  appId: "1:745737502175:web:a26e5b0baa3769c9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);


var messagesRef = firebase.database().ref('messages');


document.getElementById('contactForm').addEventListener('submit', submitForm);

function submitForm(e) {
  e.preventDefault();

  var name = getInputVal('name');
  var email = getInputVal('email');
  var message = getInputVal('message');

  saveMessage(name, email, message);


}

// Function get value
function getInputVal(id) {
  return document.getElementById(id).value;
}

//Save
function saveMessage(name, email, message) {
  var newMessageRef = messagesRef.push();
  newMessageRef.set({
    name: name,
    email: email,
    message: message
  })
}
1 Answers

This error is very common and arises because either you have not configured your config object correctly or the script tag required for using that particular functionality is missing. In your case the config object looks fine so you have to add this script in your page

<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-database.js"></script>

But please note that this script is to be added only after the core script for firebase app

<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js"></script>

and for future if you want to use any other service from Firebase like Firestore or so, just make sure you have that particular script tag in there (with the config object correctly setted up).

Related