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.
// 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
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 theuser ID
?Compare to :
Update :
There it work for me :
I did as I mention above and added the
task.id
instead ofuser.id
and then I removed theres.ok
just tores
as for me at least it complain onok
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
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 ?
OK
. (of course, the API is responding with OK status though the task is not being stored )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 containingcompleted : true