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.
// 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
You need to pass id
@click="deleteTask(task.id)"
and in method:You are receiving 404 because you a calling
https://dummyjson.com/todos/undefined
1 – You need to dispatch the id:
2 – also, call the "deleteTask" method with the id:
after that, you will call
https://dummyjson.com/todos/1