Troubleshooting Issue: Vue.js and Firebase not synchronized after deleting document

I am currently developing a web application that allows users to add and remove notifications.

To facilitate the deletion process in Firestore, I have included an ID field in the notification document, which is also added to the data-id attribute in the DOM. This allows me to use the .where method to locate the document and delete it.

However, a challenge arises when I call the getNotifications() function to update the DOM. It appears that there is a slight delay in deleting the document, causing getNotifications() to execute before the document is fully removed. As a result, the deleted notification may still be displayed on the DOM.

I attempted a solution by adding a 100-millisecond timeout before calling the function, which seemed to work, but it does not feel like the most optimal approach.

Does anyone have a better solution to this issue? Any assistance would be greatly appreciated! :)

export default {
        data() {
            return {
                messages: []
            }
        },

methods: {
    getNotifications() {
        const self = this;
        const db = firebase.firestore()
        this.messages = [];
        db.collection("messages").get()
            .then(function(snapshot){
                snapshot.forEach(function(doc){
                    self.messages.push(doc.data());
                })
            })
    },

    deleteNotification(e) {
        const self = this;
        const id = e.target.parentElement.parentElement.getAttribute("data-id");
        const db = firebase.firestore()
        db.collection("messages").where("id", "==", id).get()
            .then(function(res) {
                res.forEach(function(doc) {
                    doc.ref.delete();
                    console.log("Document deleted")
                })
            })
            .then(function() {
                self.getNotifications();
            })
            .catch(function(error) {
                console.log("Error deleting document: ", error)
            })
    }
},

created() {
    this.getNotifications()
}
}

Answer №1

When I first started working with Firebase, I encountered a similar issue. One effective solution is to implement realtime updates. By configuring the getNotifications() method to load notifications initially and subscribe to updates, you can automate the process of refreshing notifications upon deletion. The subscriptions are designed to react to deletions almost instantly, saving you the trouble of manual refresh.

For more information, refer to the documentation provided on this page.

Answer №2

Here are a couple of tips:

  1. If you have the ID already, you don't need to retrieve the document to delete it. You can simply use this code snippet:
const reference = db.collection("messages").doc(id)
await reference.delete()
  1. Your current code isn't functioning because you are executing an asynchronous action to delete the document, but you are not waiting for it to complete before moving on to the next block of code. This setup may lead to nested .then/.catch blocks, which is not recommended.
  2. Take a look at Async/Await for a better approach :)

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

Embed Javascript Code Within Text Field

Is there a way to incorporate this JavaScript into the "price" text value? Below is the code snippet: <script> function myFunction() { var x = document.getElementById('car-select')[document.getElementById('car-selec ...

Utilizing a switch to deactivate all currently active classes on individual div elements

I'm currently facing an issue with implementing a toggle feature in a particle manner. I have three divs with onclick events and each has a toggle CSS class. My goal is to ensure that when one div is clicked, if the others are active, they revert back ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

What is the process for programmatically importing a module into the local scope in Node.js?

The coding environment is using a browser and the bundle tool being used is webpack. In my router.js file, I have the following code: import foo from './views/foo.vue' import bar from './views/bar.vue' import zoo from './views/zoo. ...

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

Experiencing Excessive Recursion While Dynamically Attaching Click Event Listener With Post Method to a Div Element

I'm encountering 'too much recursion' errors when trying to dynamically add a click handler to specific div tags with the class name 'reportLink'. Despite successfully logging the innerText of the divs, the code fails when attempti ...

Is it possible for AJAX to access files with unique extensions?

I recently discovered some files with the extension .cst on my localhost server. I'm wondering if AJAX is capable of loading them. So, here's my question: Can AJAX load files with custom extensions? If yes, how can I achieve this? If not, is ther ...

What is the process of passing a JavaScript variable to PHP with AJAX?

In the given scenario, I have an HTML file that is intended to display the content of a text file at div id="myDiv". The text file content will be read by PHP. However, there seems to be an issue in retrieving the content from the text file. I need assis ...

After clicking on a specific href element with a designated class, trigger the display of a custom dialog styled using CSS

I recently added a unique class to certain links on my website. When these specific links are clicked, I want them to trigger a customized dialog box. My goal is to modify the CSS of this special dialog box. Only links with this particular class should ...

vuejs default properties initialized with vue-i18n

I am trying to establish a default property from a dictionary in this way: props: { title: { type: String, default: this.$t("basic.confirm"), }, description: { type: String, } }, ... The $t function is part of the vu ...

CSS radio button not showing up on Safari browser

I am encountering an issue with my vue app where it functions correctly on Google Chrome but experiences problems on Safari. Specifically, the issue arises with components containing radio buttons. Upon clicking on a radio option, the selected color (blue) ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

"Using VueJS to allow for easy data editing directly from a table and redirect

I currently have 3 pages set up for my project: 1- The first page is a list displaying all the data in a table format. 2- The second page allows me to add new data (currently using dummy data in the code). 3- The third page is supposed to be an edit page, ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Utilizing Page Objects to select dropdown list items in JavaScript for Protractor testing

I'm struggling with a particular issue during my testing process. The task requires selecting an item from a list as part of a form to create a new user. However, the test does not select an item from the list even though Protractor does not report an ...

Automatically insert content into a div following the execution of an AJAX delete function using jQuery

I've been working on a feature to display an auto-populated message in the results div when a user deletes the last item from their favorites list, indicating that it is empty. However, I've hit a roadblock and can't seem to make it work. H ...