Skip to content
Advertisement

Firebase Database code not working after window.location is inserted in JS

This is the code of JS file makeroom.js- The database part doesn’t work after the window.location code is put. Any solutions?

var firebaseConfig = {
    apiKey: "AIzaSyD96Lgszg8M9TptKknYlfnCDsEfy9ZO2dQ",
    authDomain: "hwforfirebase.firebaseapp.com",
    databaseURL: "https://hwforfirebase.firebaseio.com",
    projectId: "hwforfirebase",
    storageBucket: "hwforfirebase.appspot.com",
    messagingSenderId: "297251167674",
    appId: "1:297251167674:web:ac070375a455971c7b1183",
    measurementId: "G-Z7PPXV5NEJ"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

document.getElementById("greeting_para").innerHTML = "Welcome," + " " + localStorage.getItem("NameForChatApp") + " " + "!";
function addRoom(){
      RoomName = document.getElementById("makeroom_input").value;
      localStorage.setItem("Room Name",RoomName);

      firebase.database().ref("/").child(RoomName).update({
            purpose: "Adding Room Name"
      });


      window.location = "chatscreen.html";



}

Advertisement

Answer

Writing data to the database is an asynchronous operation, and it may take some time. Right now you’re setting the window.location before the write is sent to the database. To ensure that write completes, you must wait with changing the location.

The simplest way to do that is by waiting until the then() of the update method gets called:

firebase.database().ref("/").child(RoomName).update({
    purpose: "Adding Room Name"
}).then(function() {
    window.location = "chatscreen.html";
});
Advertisement