Naser Ahadi
Naser Ahadi

Reputation: 51

why data in data tabel is not deleting without refreshing the page?

I have delete button, and when I press this button It is working and deleting the row but I should refresh the page to disappear that row. How can solve this problem and deleting the row without refreshing the page?

actions:

   deleteItem({commit}, pk) {
          axios.delete(`/myurl/${pk}`)
               .then(() => {
                 commit('removeItem', pk)
                }).catch(function (error) {
              //eslint-disable-next-line no-console
              console.log(error)
          })
       },

mutations:

  removeItem: (state, pk) => (state.allLists = 
       state.allLists.filter(item => item.pk !== pk)),

button:

  <v-data-table
       :items="allLists"
       :headers="headers"
       :search="search"
  >
       <template v-slot:item.action="{ item }">
           <v-row>
               <v-btn
                     small
                     text
                     dark
                     color="primary"
                     class="mb-2"
                     @click="del(item.pk)"
                >
                    <v-icon>mdi-delete</v-icon>
                </v-btn>
            </v-row>
        </template>
   </v-data-table>

methods:

 methods: {
            ...mapActions(['fetchList', 'deleteItem', 'addItem']),

           del(ev) {
                 this.deleteItem(ev)
                },
          },
    }

Upvotes: 2

Views: 414

Answers (1)

James Totty
James Totty

Reputation: 222

Your mutation removeItem is actually returning state.allLists = state.allLists.filter(item => item.pk !== pk).

This is because you are using round brackets (). You should use curly brackets {}. Your mutation should look as following:

removeItem: (state, pk) => {
    state.allLists = state.allLists.filter(item => item.pk !== pk)
}

Generally speaking you want to avoid mutating the original array. It would be better to find the index of the item you want to remove and splice it. For example:

removeItem: (state, pk) => {
    const index = state.allLists.findIndex(item => item.id === pk.id);
    state.allLists.splice(index, 1);
}

This way when you access the state in your component it should be reactive and render the correct values without having to reload the page.

By the way how are you accessing allLists in your component?

Upvotes: 1

Related Questions