I’m expecting to add a new task object and visualize it in the parent component array by clicking the Add button. But I’m havingg an error newTask is not defined. Even though I’m forming the newTasks in the child component and passing it to the parent array in the vuex.
// Child component
methods: {
addTask() {
let newTask = {
id: Math.floor(Math.random() * 25),
title: this.title,
completed: false,
};
if (newTask) {
console.log(newTask);
this.$store.dispatch('addTask', newTask);
this.title = '';
}
},
}
// Store
export const state = () => ({
tasks: [],
});
const actions: {
async addTask(context, data) {
data = {
...data,
newTask, // getting an error here - newTask is not defined
};
const res = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
headers: {
'Content-Type': 'appication/json;charset=utf-8',
},
body: JSON.stringify(data),
});
if (res.ok) {
let result = await res.json();
context.dispatch('getTasks');
}
return res.ok;
},
}
const mutations: {
setTasks(state, data) {
state.tasks = data;
},
}
store
3
Answers
It looks like you’re trying to pass
newTask
as a property of thedata
object that’s being sent in theaddTask
action, butnewTask
is not defined in the scope of theactions
object.To fix this issue, you can simply remove the
newTask
property from thedata
object:You’re already passing the
newTask
object as the second argument to theaddTask
action in the child component (this.$store.dispatch('addTask', newTask)
), so it will be available as thedata
parameter in the action.Additionally, in the
setTasks
mutation, you’re setting thestate.tasks
to the entire response data object (state.tasks = data
), but you probably only want to set it to the newly added task object. To fix this, you can change the mutation to:This will add the new task to the
state.tasks
array instead of overwriting it with the entire response data object.I checked your project and I found the error.
When you call API, Backend doesn’t add newTask, This is error.
So when you get response, there isn’t newTask data that you added.
Do you have got back-end code?
I think you should modify the controller about
https://jsonplaceholder.typicode.com/todos
request.In this controller, the
addTask
request isn’t processed.The
addTask
request doesn’t insert to DB.You have to modify the controller of back-end.
And you can give me the back-end, then I will solve this error.