Creating a new Todo on the server

We'll also want to be able to create a new Todo by using HTTP post to create a new Todo. This will also be an async function since we’ll be making an async call to fetch to send data. Since posting via HTTP is more complicated than getting, we’ll also need to specify some options into our fetch call. Specifically, we can configure the call by specifying the HTTP method (POST in our case), the headers (just an accept header for JSON data, which is the same as what we’d normally use to communicate with any JSON API), and the body of what we’re posting to the server, which is just the data structure of a new Todo. If it is successful, we will add the new Todo onto our state and call it a day. Back in src/TodoList/TodoList.js, as follows:

  async addTodo(description) {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { accept: 'application/json', 'content-type': 'application/json' },
body: JSON.stringify({ description: description, critical: false, done: false })
});
if (res.status === 200) {
const newItem = {
id: this.state.items.length + 1,
description: description,
done: false,
critical: false
};
this.setState({
items: [...this.state.items, newItem]
});
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.211.87