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:
- Create a new src/api.js file.
- 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())
}
- 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.