[Vuejs]-How to delete nested Firebase data with Vue.js

0đź‘Ť

There are two pieces of code in your question (somehow two linked but different questions): an initial one and one after the REVISION.

Let’s first give the answer for the initial question: with your Vue.js component code you need to have a users array that looks like:

  users: [
    {
      id: 1,
      gallery: [
        { id: 11, image: "http://...image1.jpg" },
        { id: 12, image: "http://...image2.jpg" },
        { id: 13, image: "http://...image3.jpg" }
      ]
    },
    {
      id: 2,
      gallery: [
        { id: 21, image: "http://...image1.jpg" },
        { id: 22, image: "http://...image2.jpg" },
        { id: 23, image: "http://...image3.jpg" }
      ]
    }
  ]

It means you have to “construct” your Firestore documents in such a way they return an array with this format.


For the second problem (after the REVISION sub-title):

You should use the optional second argument of v-for to get the index of the current item and call the deleteInput() with this index value plus the user.id, as follows:

<div v-for="user in users" :key="user.id">
  <div v-for="(newUser, index) in user.events" :key="newUser.id">
    <h3>{{ newUser.name }}</h3>
    <button @click="deleteInput(user.id, index)">x</button>
  </div>
</div>

Then in deleteInput() you need to

either

overwrite the events array for the user (with id == user.id) with a new events array, in which you have deleted the element at position index,

or

use the arrayRemove() method with the entire object (events, email, name, etc…).

I would opt for the first approach.

Note that depending on your exact use case you may have to do that in a transaction, to be sure the events array was not modified between the initial read and the modifciation.

Leave a comment