Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete a task in a todo list?

I’m expecting to delete an individual task in the array via DELETE request, but I’m having the 404 error, even though the url is correct and I’m passing the userId in the method, or should I use id instead. Meanwhile the url array has both – the userId and the id for each element.

https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=pages%2Findex.vue,store%2Findex.js,components%2FTask.vue

// Child component

<template>
  <div :class="{ task: task.completed }">
    {{ task.todo }}
    <button @click="deleteTask" class="delete">Delete</button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: ['task'],
    deleteTask(userId) {
      this.$store.dispatch('deleteTask');
    },
  },
};
</script>

// Parent component

<template>
  <Task v-for="task in tasks" :key="task.id" :task="task" />
</template>

<script>
export default {
  data() {
    return {
      todo: '',
      completed: false,

    };
  },
  computed: {
    tasks() {
      return this.$store.state.tasks;
    },
  },
  created() {
    this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
  },
  methods: {
  },
};
</script>

// Store 

export const state = () => ({
  tasks: [],
});

export const actions = {
  async getTasks(context) {
    const res = await fetch('https://dummyjson.com/todos');
    if (res.ok) {
      let result = await res.json();
      context.commit('setTasks', result.todos);
    }
    return res.ok;
  },
  async deleteTask(context, id) {
    const res = await fetch(`https://dummyjson.com/todos/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
    });
    if (res.ok) {
      let result = await res.json();
      context.dispatch('getTasks');
    }
    return res.ok;
  }
};

export const mutations = {
  setTasks(state, data) {
    state.tasks = data;
  }
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to pass id @click="deleteTask(task.id)" and in method:

deleteTask(id) {
  this.$store.dispatch('deleteTask', id);
},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading