Home > database >  Firebase Realtime Database not saving data when I add "location.replace"
Firebase Realtime Database not saving data when I add "location.replace"

Time:01-16

I am trying to push data to Firebase Real-time Database and after the data is pushed(and saved), the browser should open another page. I have used "location.replace()" function to open the next page however adding the location.replace line makes the data not to be saved in Firebase real-time database.

Here is my code

var updates = {};
updates['/users/'   document.getElementById('username').value] = data;
firebase.database().ref().update(updates);
console.log("Saved successfully")
location.replace("nextpage.html");

CodePudding user response:

The update function is asyncronous; it will take some time to complete. If you want to wait until the update is done, then you will need to use the promise it returns:

var updates = {};
updates['/users/'   document.getElementById('username').value] = data;
firebase.database().ref().update(updates)
  .then(() => {
    console.log('Saved successfully');
    location.replace('nextpage.html');
  });

Or with async/await:

async function someFunction () {
  var updates = {};
  updates['/users/'   document.getElementById('username').value] = data;
  await firebase.database().ref().update(updates);
  console.log("Saved successfully")
  location.replace("nextpage.html");
}

CodePudding user response:

the update seems to be asynchronous function, returning a promise. so you should properly handle it. Otherwise call to "location" may come before the update is finished.

Change it like this:

firebase.database().ref().update(updates).then(() => {
  console.log("Saved successfully")
  location.replace("nextpage.html");
}).catch(error => {console.log('Error:', error)})

If you don't want to use promise, provide an additional argument to the update function that will serve as a callback function, i.e will be called when update is finished:

firebase.database().ref().update(updates, function() {
  console.log("Saved successfully")
  location.replace("nextpage.html");
})
 
  •  Tags:  
  • Related