Parent array gets removed when updating the array inside an array. I only want the nested array to get updated. How to solve it? below is my code:
const handleSubmit = async (e) => {
e.preventDefault();
const commentToAdd = {
displayName: user.displayName,
photoURL: user.photoURL,
content: newComment,
createdAt: timestamp.fromDate(new Date()),
id: Math.random()
}
await updateDocument(project.id, {
tasks: [ {
comments: [{...project.tasks.comments, commentToAdd}],
}
]
})
CodePudding user response:
Firestore doesn't support updating array elements at given index. You first need to fetch the document, update array field with relevant data and update the whole array back. Nested arrays will make it even more complex to update a nested item.
You can simply this a bit by creating a sub collection for tasks as shown below:
projects -> { projectId } -> tasks -> { taskId }
This way each task document will have a comments array. However, you'll still have to read the comments and then write updated array back.
CodePudding user response:
Like @Dharmaraj said, Firestore doesn't support updating array elements at given index.
As far as I understand your question. If you want that parent Array not to be removed, and just update/add commentsToAdd
in the comments
array. You could also use setDoc
as opposed to updateDoc
. See below code for example.
for (let step = 0; step < 5; step ) {
const commentToAdd = {
displayName: `someName-${step}`,
photoURL: `someURL-${step}`,
content: `someContent-${step}`,
createdAt: new Date(),
id: Math.random()
};
await setDoc({someRef}, {
tasks: {
comments: arrayUnion(commentToAdd)
}
}, {merge: true})
}
The code above would result to:
I looped the code to push multiple comments on the field. Just a note, by doing this, you're field types will be updated accordingly:
- tasks: `map`
- comments: `array`
- commentFields: `map`
You may also refer to this documentation for more information.