Skip to content
Advertisement

Firestore Array of map not updating

So I’m working on a personal project to learn react-native and Firestore.

I have a DB like this:

Db image

And I want my code to add a new battery in the array batteries. The elements in the array are just a map{string, string}

The problem is that when I update the array with a new brand that’s work but if I want to update it with the same brand again have, so having by the end

batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}

The DB doesn’t update, doesn’t have any error or so.

I don’t understand why and I followed their tutorial. Here is my code:

async function addData(collection, doc, value) {
    console.log(`Add data ${value.brand}`)
    try {
        const result = await firestore()
                    .collection(collection)
                    .doc(doc)
                    .set({
                        batteries: firestore.FieldValue.arrayUnion(value)
                    })
        console.log(result);
        return result;
    } catch (error) {
        return error;
    }
}

I use try-catch by habit but I don’t know if the then...catch is better or not.

Advertisement

Answer

arrayUnion says that it “adds elements to an array but only elements not already present”. Maybe it does a stringify or something to check equality and therefore doesn’t add the new element. I think you’ll have to 1. get the current list, 2. add your element, 3. set the batteries field to the updated list.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement