skip to Main Content

After creating a new to do item in the list, after clicking the delete button all of the new tasks are deleted insetead the single one. I’m expecting to be deleted only the propriete one with a passed id with it.

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

// Child component

<template>
    <p class="content">
      {{ task.todo }}
    </p>
    <button @click="() => deleteTask(task.userId)" class="delete">
      Delete
    </button>
</template>

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

// Parent component

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

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

// Store

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

export const actions = {
  async getTasks(context) {
    const res = await fetch('https://dummyjson.com/todos/user/5');
    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': 'appication/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;
  },
};

2

Answers


  1. Correct me if I’m wrong but shouldn’t be that you are passing in the task ID of the task you want to delete and not the user ID?

    <button @click="() => deleteTask(task.id)" class="delete">
      Delete
    </button>

    Compare to :

        <button @click="() => deleteTask(task.userId)" class="delete">
          Delete
        </button>

    Update :

    There it work for me :

     async deleteTask(context, id) {
        const res = await fetch(`https://dummyjson.com/todos/${id}`, {
          method: 'DELETE',
        })
          .then((res) => res.json())
          .then(console.log);
        if (res) {
          let result = await res.json();
          context.dispatch('getTasks');
        }
        return res;
      }
    completed: true
    deletedOn: "2023-05-06T14:01:35.302Z"
    id: 103
    isDeleted: true
    todo: "Go to a local thrift shop"
    userId: 5

    I did as I mention above and added the task.id instead of user.id and then I removed the res.ok just to res as for me at least it complain on ok part.

    Then added .then and removed the headers. I don’t think it matters but I looked at the docs and the example didn’t use it so.

    The only thing left for you is to update the list and maybe add some error handling if something doesn’t goes as planned

    Login or Signup to reply.
  2. The issue is not with the DELETE functionality!!
    When I looked the code and the API responses, the issue is not with the delete functionality.
    The issue is with the todos/add API through which you create a new task.
    I could see the response with json including the completed: false, indicating that the task has not been created.

    Then why is it showing as a new task when created and why all new tasks are vanishing on deleting a particular task ?

    1. While creating a new task, you are appending the task to your tasks list when the API response is OK. (of course, the API is responding with OK status though the task is not being stored )
    2. Once after deleting of a particular task, You are re-fetching the task list from the server ( and it’ll give only those tasks which are being stored. And as I mentioned earlier, no task is being saved so it appears that it deleted all the tasks instead of one

    What to do now ?
    You better go, look at the backend where you wrote the code to store the tasks and check why it’s not being stored.

    NOTE : Once after creating the tasks, you are looking at the status to be OK, you better also look for the response with containing completed : true

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search