0👍
✅
First, You pass task
to method:
<button @click="toggleTask(task)">
{{ task.completed ? 'Undone' : 'Done' }}
</button>
then in Vuex create action that will put data and commit mutation:
async toggleTask(context, task) {
const res = await fetch(`https://dummyjson.com/todos/${task.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify({completed: !task.completed}),
})
let result = await res.json();
context.commit('updateTask', result)
},
at the end mutation:
updateTask(state, task) {
state.tasks = [
...state.tasks.map(item =>
item.id !== task.id ? item : {...item, ...task}
)
]
},
0👍
In the click handler
toggleTask(id) {
this.$store.dispatch('toggleTask', id);
},
id is an event object. You need to properly pass the id here. Below should work
this.$store.dispatch('toggleTask', this.task.id);
Source:stackexchange.com