Unable to remove document from firestore

I'm utilizing Vuex for state management in my web application. I encountered an issue while trying to delete a document from my Firestore database - clicking the button does not trigger any action.

Here is a snippet of the card header containing a delete icon, meant to delete the document upon clicking:

<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 mutation for deleting a stock is defined as follows:

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

The action for deleting a stock is structured like this:

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

This is where the deleteStock action is invoked within the template's methods section:

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

Despite setting up everything correctly, clicking on the delete icon doesn't trigger any response.

Answer №1

The issue arises from the utilization of an asynchronous function within your mutations in vuex, however, the vuex documentation makes it clear:

Mutations Must Be Synchronous

To resolve this issue, you should execute the async call to the database inside your action instead

  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);
           });
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the sound levels of an HTML audio element using JavaScript

I'm looking to adjust the volume of an <audio> element when a user clicks on an image. HTML: <div id="cloud"> <img name="jsVolumeButton" src="images/cloud.png" width = "140px"/> </div> <audio id="player" src="sounds/rain. ...

Error: When trying to run npm start in a React project, an issue arises where the property 'prototype' is undefined and results in

Having trouble while running my react app, I am encountering an issue. Can someone please assist me with this? A TypeError is showing up: "Cannot read property 'prototype' of undefined". This error is displayed on the browser page. The terminal o ...

Transform the blob data into an Excel file for easy download, but beware the file is not accessible

My API returns a response containing the content of an excel file, which is displayed in the image below. https://i.sstatic.net/2VHsL.png Now, I am looking to convert this content into an excel file and make it downloadable for the user. Below is the AP ...

Prevent default behavior when a radio button is clicked

I have a form with two radio buttons, and I want to prevent either of them from being checked. Disabling them is not an option because I still need the selected value to be submitted to the database. When one button is clicked, it gets checked but then doe ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Automatic resizing of line charts in Angular with nvd3

I'm currently utilizing AngularNVD3 directives. Referencing the example at: https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives/blob/master/examples/lineChart.with.automatic.resize.html <!-- width and height have been removed f ...

Learning to dynamically access files from various folders and subfolders within webpack using JavaScript

I'm currently working on a project in VueJs using webpack. As part of this, I need to dynamically include config/routing files from specific folders. Here is an example of my folder structure: plugins |----Ecommerce |--------backend |--------frontend ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Send information to MongoDB following a GET request in Node.js

When it comes to transferring data from Node's http.get() to mongoDB using mongoose, I'm encountering some challenges. I'm unsure of how to integrate the GET result into mongoose's methods. Here are a few queries regarding the process: ...

What is the best way to trigger a re-render of a Vue component after a change in Vuex

I'm interested in developing a custom component to modify the basemap of a leaflet map without relying on L.control.layers. To achieve this, I created a sidebar component that offers options to switch between different basemaps. In my implementation, ...

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

When using AngularJS and PHP together, I encountered an error that stated "

My POST http request is encountering an error with the message Undefined property: stdClass::$number and Undefined property: stdClass::$message. Below are the codes I've been using: smsController.js angular .module('smsApp') .contr ...

What is the correct method for checking the balances of various tokens in my MetaMask wallet?

I've been trying to figure out how to check the balance of Alpaca tokens in my MetaMask wallet. After doing some research, I came across a code snippet that I tried to use but it ended up throwing an error: TypeError: contract.balanceOf is not a fun ...

Swipe to eliminate an element in Ruby on Rails

I am looking to implement a drag-and-drop delete feature on my website, similar to the recycle bin/trash function on Windows or OSX. Within my database, I have multiple objects represented by div elements using Ruby. While I know how to add drag functiona ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

JavaScript is causing performance issues in Selenium with Python

I am facing a challenge with web scraping a site that utilizes JavaScript/AJAX to load more content as you scroll down. My setup involves Python 3.7 and Selenium Chrome in headless mode. However, I've noticed that as the scraping process continues, th ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

The FlexDirection property in React Native is malfunctioning when set to 'row'

I'm having trouble getting these items to display in a row horizontally, and I can't figure out why. Any assistance would be greatly appreciated! const TextComponent = () => { const Menu = [ {'id':1, 'menuName':'F ...

Is it necessary to have nodejs, or can I just depend on Nginx alone?

I am currently in the midst of a discussion with my colleagues regarding whether or not to incorporate node.js into our application. We have decided to utilize angular.js for the front-end and communicate with the app server through a REST api. The app ...