Search code examples
mongodbvue.jsvuex

Why does delete method not updated the list?


Working Todo application using VueJS, Vuex and MongoDB, after delete a task my list does not updated without refresh page. I already add a dispatch GET_TASK in promise awaiting the list update, but it is not working, and seems which this promise even not execute.

<template>
    <div class="flex-col mx-auto mt-10 min-w-max font-sans text-xl" style="width:512px">
        <ul class="space-y-2">
            <li class="flex justify-between px-4 min-h-full" v-for="task in tasks" :key="task.id">
                {{task.task}} 
                <button @click="deletetodo(task._id)" class="text-xs border-2 px-4 focus:outline-none hover:bg-blue-200 hover:text-white rounded-full">Delete</button>    
             </li>
        </ul>
    </div>
</template>

<script>
export default {
    name:"ListToDo",
    computed:{
        tasks: function(){
            return this.$store.state.task
        }
    },
    methods:{
        async getlisttodo(){
            await this.$store.dispatch("GET_TASK")
        },
        async deletetodo(id){
            await this.$store.dispatch("DELETE_TASK",{'id':id})
            .then(response => {
                this.$store.dispatch("GET_TASK")
                console.log(response);
            })
            .catch(error => console.log(`DeleteTodo ${error}`))
        }
    },
    mounted(){
        this.getlisttodo()
    }
}
</script>

Vuex:

   actions: {
        async GET_TASK({ commit }) {
            const rawResponse = await fetch('http://localhost:3000/tasks')
            const content = await rawResponse.json();
            commit("SET_TASK", content)
        },

        async SAVE_TASK({ commit }, object) {
            const rawResponse = await fetch('http://localhost:3000/save', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'task': object })
            });
            const content = await rawResponse.json();
            commit("SET_MESSAGE", content)
        },

        async DELETE_TASK({ commit }, obj) {
            const id = obj['id']
            const raw = await fetch(`http://localhost:3000/delete/${id}`, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'id': id })
            });
            const content = await raw.json();
            commit("SET_MESSAGE", content)
        }
    }

Solution

  • I got to fix that by adding DELETE METHOD

    vuex:

    async DELETE_TASK({ commit }, obj) {
        try {
            const id = obj['id']
            const raw = await fetch(`http://localhost:3000/delete/${id}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'id': id })
            });
            const content = await raw.json();
            commit("SET_MESSAGE", content)
        } catch (error) {
            console.log(`DELETE_TASK ${error}`)
        }
    }
    

    server.js

    app.delete('/delete/:id', async(req, res) => {
        try {
            const id = req.body.id;
            TodoTask.findByIdAndDelete(id, err => {
                if (err) return res.send(500, err);
                res.send({ 'status': 200, "mensagem": 'Tarefa deletada' })
            })
        } catch (error) {
            console.log(`Error Delete ${error}`)
        }
    })
    

    ListTodo.vue

    methods:{        
        async deletetodo(id){
            try{
                await this.$store.dispatch("DELETE_TASK",{'id':id})
                .then(response => {
                    this.$store.dispatch("GET_TASK");
                    console.log(response);
                }) 
                .catch(error => console.log(error))
            }catch(error){
                console.log(`DeleteTodo ${error}`);
            }
        }
    }