I'm expecting to visualize a new task todo title at the top of the tasks array after clicking the Add. button. I'm doing it with POST request fake API, but having the error 404 and I can't see the added todo on the page. Even though I get the new task object in the console.
// Store
const actions: {
const res = await fetch('https://dummyjson.com/todos/add', {
method: 'POST',
headers: {
'Content-Type': 'appication/json;charset=utf-8',
},
body: JSON.stringify(data),
});
if (res.ok) {
let result = await res.json();
context.commit('addnewTask', result);
}
return res.ok;
},
}
export const mutations = {
addnewTask(state, newTask) {
state.tasks.unshift(newTask);
},
}
// Child component
<template>
<div class="create-new">
<input
type="text"
v-model="todo"
@keypress.enter="addTask"
placeholder="add task"
/>
<button @click="addTask">Add</button>
</div>
<div class="tasks">
<Task v-for="task in tasks" :key="task.id" :task="task" />
</div>
</main>
</template>
<script>
export default {
data() {
return {
todo: '',
completed: false,
search: '',
};
},
computed: {
tasks() {
return this.$store.state.tasks;
}
methods: {
addTask() {
let newTask = {
id: Math.floor(Math.random() * 25 + 200),
todo: this.todo,
completed: false,
};
if (newTask) {
this.$store.dispatch('addTask', newTask);
}
},
It's not a 404, it's a 400, which indicates some client side mistake. Looking at the network tab in the browser dev tools, the response from dummyjson.com has this:
{"message":"User id is required"}
Checking the docs,
https://dummyjson.com/docs/todos#add, it does show a userId
as part of the request body
body: JSON.stringify({
todo: 'Use DummyJSON in the project',
completed: false,
userId: 5,
})
whereas your request has id
instead of userId
. Also realize that jsondummy.com only has user ids in the range of 1 - 100. Sending any userId outside that range will generate another error.
You have one other issue involving a typo here:
'Content-Type': 'appication/json;charset=utf-8',
where appication should be application