skip to Main Content

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;
  }
};

2

Answers


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

    deleteTask(id) {
      this.$store.dispatch('deleteTask', id);
    },
    
    Login or Signup to reply.
  2. You are receiving 404 because you a calling https://dummyjson.com/todos/undefined

    1 – You need to dispatch the id:

      // Task.vue - line 26
      deleteTask(id) {
            this.$store.dispatch('deleteTask', id);
      },
    

    2 – also, call the "deleteTask" method with the id:

      // Task.vue - line 10
      <button @click="() => deleteTask(task.id)" class="delete">Delete</button>
    

    after that, you will call https://dummyjson.com/todos/1

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