Search code examples
javascriptfirebasevue.jsgoogle-cloud-firestorevuex

Document not getting deleted in firestore


I'm using Vuex form my state management in my web app. I wanted to delete a document from my firestore database but when I click the button nothing happens.

This is segement of the card header with a delete icon so when clicked it deletes the document:

<div class="card">
      <div class="card-header card-head-color">
        <span class="card-header-text"
          >{{ stock.name }} <small>(Price: {{ stock.price }})</small></span
        >
        <i
          class="fa fa-trash-alt float-right trash-icon"
          aria-hidden="true"
          @click="deleteStock(stock.key)"
        ></i>
      </div>

The delete stock mutation is as follows:

DELETE_STOCK(id) {
    db.collection("stocks")
      .doc(id)
      .delete()
      .then(() => {
        console.log("Document Deleted!");
      });
  },  

The delete stock action is:

  deleteStock: ({ commit }, id) => {
    commit("DELETE_STOCK", id);
  },

This is where the delete stock action is called in the template inside methods:

   deleteStock(id) {
      this.$store.dispatch("deleteStock", id);
    },

But whenever I click the Icon nothing happens.


Solution

  • The reason is that you are using an async function inside your mutations in vuex, but the vuex documentation clearly states:

    Mutations Must Be Synchronous

    To fix this problem, you should do the async call to db inside your action

      deleteStock: ({ commit }, id) => {
           db.collection("stocks")
             .doc(id)
             .delete()
             .then(() => {
                console.log("Document Deleted!");
                //now you can commit and remove it from the state
                commit("DELETE_STOCK", id);
               });
      },