I am encountering a 404 error while trying to delete an individual task from the array using a DELETE request. The URL is correct and I am passing the userId in the method, but should I be using id instead? It's worth noting that the URL array contains 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;
}
};