Home > Net >  Firebase Batch set with invalid data
Firebase Batch set with invalid data

Time:11-19

Error Message: Function WriteBatch.set() called with invalid data. Data must be an object, but it was: www.google.com

I have a button that onclick runs the addQuotes function.

Where am I going wrong?

const addQuotes = async () => {
      let test = ['https://www.google.com/', 'https://www.google.com/about',]
      const obj1 = Object.assign({}, test);
      const batch = writeBatch(db);

Object.keys(obj1).forEach(key => {
  var docRef = db.collection("col").doc(); //automatically generate unique id
  batch.set(docRef, obj1[key]);
});

 batch.commit().then(function () {
        console.log("hello")
    });
}

CodePudding user response:

As the error says, the data param should be an object (second argument to the batch.set method)

  • Commented out the firebase methods invocation for running the code and show you the o/p

// In your case when you do 
let test = ['https://www.google.com/', 'https://www.google.com/about', ]
const obj1 = Object.assign({}, test);

console.log(obj1);


// and ignoring the unique id step


Object.keys(obj1).forEach((key, index) => {
  // var docRef = db.collection("col").doc(); //automatically generate unique id
  
  console.log(obj1[key]);  // here it is just the string value
  
  console.log({[index]: obj1[key]}); // here it is an object
  
  //when you do the bellow line
  // batch.set(docRef, obj1[key]); // value of obj1[key] is just string which is not the correct type 
  
  // may be you do something as below (key can be as you want it to be)
  // batch.set(docRef, {[index]: obj1[key]});  // index is added as key for the object which in now an object and should work
  
});

I used {[index] : obj1[key]} notation which is computed property in object

Hope it's clear

  • Related