Building service libraries

We'll start off by moving all of our API calls into a new file, src/TodoService.js. We'll start with the simplest call, which is the call to fetchTodos items from the server:

const fetchTodos = async () => {
const res = await fetch("/api/todos", { accept: "application/json" });
const json = await res.json();
return { status: res.status, todos: json.todos };
};

Here, we've written our fetchTodos() function as an async function that, for the most part, does what it did originally. The only major different here is that we've changed the return statement to not just send back the list of todos from the server, but also the HTTP status code from the server!

Next, we'll implement the call to create a Todo on the server:

const createTodo = async description => {
const res = await fetch("/api/todos", {
method: "POST",
headers: { accept: "application/json" },
body: JSON.stringify({
description: description,
critical: false,
done: false
})
});
const json = await res.json();
return { status: res.status, todos: json.todos };
};

Again, this post is almost identical to what you saw previously, except with the modification around the return statement. Finally, we'll move on to the delete call on our server:

const deleteTodo = async todoId => {
const res = await fetch(`/api/todos/${todoId}`, {
method: "DELETE",
headers: { accept: "application/json" }
});
const json = await res.json();
return { status: res.status, todos: json.todos };
};

We've added a few functions, so we'll export them at the end of the service library. All we need to do is export these three functions as named functions:

export { fetchTodos, createTodo, deleteTodo };
..................Content has been hidden....................

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