Home > OS >  FirebaseError: Function DocumentReference.update() called with invalid data. Nested arrays are not s
FirebaseError: Function DocumentReference.update() called with invalid data. Nested arrays are not s

Time:04-12

enter image description here.enter image description here I am trying to implement the add-to-cart feature with my firebase using firestore.

I have a fetch function that gets any existing item that is in the cart already. But all I need is the value in the Array items but when I add it to my fectchedcartItems list, it creates a nested array which gives me issues when I am trying to update the cart as it doesn't support nested array. Is there a way to just get the values and not create a nested array? fetchItems = () => {

    Fire.shared.firestore.collection("cart").where("userId", "==", this.state.uid).get().then((qSnap) => {
        let itemList = []
        qSnap.docs.forEach(item => {
            itemList.push(item.data().items)
            this.setState({
                fetchedcartItems: itemList
            })

        })
       
        console.log("fectched product", this.state.fetchedcartItems);

    });

}


addItemToCart = () => {
    
        this.fetchItems()
        let items = this.state.fetchedcartItems

        items.push({ item: this.state.name, userId: this.state.uid })
        this.setState({
            items: items,
            fectchingitemsloading: true,
        },
            () => Fire.shared
                .firestore
                .collection('cart')
                .doc(this.state.cartId)
                .update({
                    items: items
                })
                .then(() => this.fetchItems())
        )

}

CodePudding user response:

let itemList = []
qSnap.docs.forEach(item => {
  itemList.push(item.data().items)
  this.setState({
    fetchedcartItems: itemList
  })
})

item.date().items appears to be an array. So when you push an array into another array, you get a nested array. Instead, you should push the individual items into the array so that you end up with just a single toplevel array:

let itemList = [];
qSnap.docs.forEach(item => {
  itemList.push(...item.data().items) // <---- added spread syntax
})
// Moved the setState outside the loop; there's no need to set state multiple times
this.setState({
  fetchedcartItems: itemList
})

Or an alternative using flatMap:

let itemList = qSnap.docs.flatMap(item => item.data().items);
this.setState({
  fetchedcartItems: itemList
})
  • Related