Defining the API code

First of all, we are going to define an API that will fetch todo items. In our case, we are simply going to return an array of todo items, after a short delay.

Let's start implementing the mock API:

  1. Create a new src/api.js file.
  2. We are going to define a function that will generate a random ID for our todo items based on the Universally Unique Identifier (UUID) function:
export const generateID = () => {
const S4 = () =>(((1+Math.random())*0x10000)|0).toString(16).substring(1)
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4())
}
  1. Then, we define the fetchAPITodos function, which returns a Promise, which resolves after a short delay:
export const fetchAPITodos = () =>
new Promise((resolve) =>
setTimeout(() => resolve([
{ id: generateID(), title: 'Write React Hooks book', completed: true },
{ id: generateID(), title: 'Promote book', completed: false }
]), 100)
)

Now, we have a function that simulates fetching todo items from an API, by returning an array after a delay of 100 ms.

..................Content has been hidden....................

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