I'm newbie and just starting coding a couple of months ago. I'm creating an app with react native with expo and I'm having trouble updating a map field into the document. So far, when I needed to update a filed(for example a name) I was doing the following:
const updateData = async () => {
await updateDoc(doc(db,"users",uid),{
name:name,
age: age,
})
The problem is that I now have a map field which stores data in the following way:
The way that I have the app set-up, is that I have an array for the food items:
const [item, setItem] = useState([
{Food: 'tomato', Calories: 20, Quantity: 1,},
{Food: 'lettuce', Calories: 10, Quantity: 1,},
]);
and I would like to store it into a map field in the firestore document.
I thought that I would be able to use a for loop, so that I can populate each field of an array element into the map, but it seems that I'm unable to use a loop inside the await.
Is there like a workaround that I would be able to use in this case?
The for loop that is being highlighted in red:
await updateDoc(doc(db,"user",uid),{
for (let i = 0; i < item.length; i ) {
}
},
{ merge: true })
CodePudding user response:
To convert the array into a map, try using reduce()
as shown below:
const updatedMap = item.reduce((a, b) => {
a[b.Food] = b;
return a;
}, {})
await updateDoc(doc(db, "user", uid), { food: updatedMap })
This will use food name as key in food map and test of the object as value.