0

I am trying to add some dummy data to firebase firestore but only the setDoc command is running twice. I don't quite understand what I'm doing wrong. This is only a .ts file, not a component file & the function is not running twice. I am sure of that. Below is my code:

import { collection, setDoc, Timestamp, doc, addDoc } from "firebase/firestore";
import { db } from "./clientApp";

type MyBrand = { name: String; image: String; dateAdded: Timestamp };
var brandCollRef = collection(db, "brand");

async function addBrands() {
    let brands: Array<MyBrand> = [];

    for (var i = 1; i <= 10; i++) {
        var myItem = {
            name: `Brand ${i}`,
            image: `https://picsum.photos/1024/1024?random=${i}`,
            dateAdded: Timestamp.now(),
        };
        brands.push(myItem);
        console.log("Added Item: " + myItem.name);
    }

    brands.forEach(async (item) => {
        // New Doc created
        const newDoc = doc(brandCollRef);
        console.log("New Doc Created: " + newDoc.id);

    // This code is running twice
        await setDoc(newDoc, item);
        console.log("Set Data in: " + newDoc.id);
    });
}

export { addBrands };

Please let me know what I'm doing wrong.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
L.Goyal
  • 773
  • 2
  • 6
  • 23
  • `setDoc` is called from within a `forEach`, it'll run for each item present in the `brands` array. Or do you mean it runs twice for _each item_ in the array? Also, you should probably have a look at [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) for a proper way to call async functions in a loop. – juliomalves Dec 21 '21 at 21:26
  • @juliomalves `setDoc` runs for each item twice. I have already tried doing the [above](https://stackoverflow.com/a/37576787/9451058) async / await method using the for loop that you mentioned but still no luck... – L.Goyal Dec 22 '21 at 06:54
  • is the issue resolved? can you refer to the link : https://stackoverflow.com/a/69901794/15774176 is this answer helpful? – Divyani Yadav Dec 27 '21 at 13:07

0 Answers0