11

How do I make this call back work? I have read the documents but I just cant figure it out for some reason?

   var ref = new Firebase("https://xxx.firebaseio.com/public/"+$scope.uid+"/shows/");
var blast = ref.child(show_title);

blast.update({
"show_title": show_title,
"show_image": show_image,
"show_description": show_description,
"show_email": show_email,
"time": Firebase.ServerValue.TIMESTAMP
});

 blast.update("I'm writing data", function(error) {
   if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});
Bill
  • 4,614
  • 13
  • 77
  • 132

3 Answers3

20

Frank's solution is perfect for your question. Another option is to use the update promise. It's particularly useful if you're doing a bunch of operations together which is often the case in Firebase.

here's an example using a promise

blast.update({ update: "I'm writing data" }).then(function(){
  alert("Data saved successfully.");
}).catch(function(error) {
  alert("Data could not be saved." + error);
});
felipesk
  • 449
  • 4
  • 5
  • 5
    That will indeed work too. Note that when the question was asked (and I answered), the [Firebase JavaScript SDK did not yet support promises](https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html). – Frank van Puffelen May 23 '17 at 13:24
  • How can one use `setState({...})` when implementing the catch() method? `this` is undefined whenever I try to use it. – Josh Jul 23 '18 at 15:51
  • @Josh It is problem of scope.the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. You should declare `const _this = this;` at first level then use `_this.setState({})` in nested method. – kansiho Aug 29 '18 at 00:04
9

Your second call to update() raises this error in the JavaScript console:

Uncaught Error: Firebase.update failed: First argument must be an object containing the children to replace.(…)

The first argument to update has to be an object, so:

blast.update({ update: "I'm writing data" }, function(error) {
  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

For reference, this is the documentation for the update() function.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

In React ES6 :

var refTypes = db.ref("products").child(productId);

var updates = {};
updates[productId] = newProduct;

refTypes.update(updates).then(()=>{
  console.log("Data saved successfully.");
}).catch((error)=> {
  console.log("Data could not be saved." + error);
});
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154