chicco.man
chicco.man

Reputation: 41

Vue.js - function not executed when data are updated

I have this function code in my vue component methods that will remove the customers data if a button is clicked and show a chrome notification.

        deleteCustomer(id) {
            console.log('deleting customer:' + id);
            db.customers.delete(id).then( () => {
            console.log('customer '+ id +' deleted!');
            browser.notifications.create('deleted',{
                type: 'basic',
                iconUrl: 'icons/128.png',
                title: 'Data removal',
                message: 'data removed with success!'
            });
            this.viewCustomers();
           });
        },

At the end of the function I'm calling another method that is supposed to call a dexie.js instance to show in a table all the customers data that are stored. When the component is mounted, all work fine with the viewCustomers function and the table is populated correctly. What I need to fix is that the method is not called after data deletion and the table isn't updating. How I can fix this, is there a vue function I can use or any code modification that can solve this problem?

Upvotes: 2

Views: 611

Answers (2)

chicco.man
chicco.man

Reputation: 41

After some headche I've found a tricky solution that will give me the ability to update the table with the updated data. I've used the onClicked method of chrome.notifications API and now all works fine, but I'm opened to every suggestion about this problem. Here is the code I've added in the mounted section of vue instance:

    mounted() {
        console.log('mounted')
        this.$set(this, 'isActive', true)
        this.viewCustomers()
        browser.notifications.onClosed.addListener( (notificationId) => {
            console.log(notificationId)
            this.customersList = [];
            this.viewCustomers();
        })
    }

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

As mentioned in the docs, Delete items is actually an async call which means it calls the this.viewCustomers() before the item is even deleted, thus it seems that it is not working. The easiest way to resolve this is to use async/await like:

async deleteCustomer(id) {
  console.log('deleting customer:' + id);
  await db.customers.delete(id);
  console.log('customer ' + id + ' deleted!');
  browser.notifications.create('deleted', {...});
  this.viewCustomers();
},

Now, the this.viewCustomers the function will be only called once the db.customers.delete() function is completed and that should result in the desired output.

Upvotes: 3

Related Questions