Created
March 23, 2022 01:51
-
-
Save natafaye/ab421d1cd09b40afdc9fef25dfdc4b6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TODO_ENDPOINT = 'https://crudcrud.com/api/f46d311529d04ee293015b2023d2b949/todos'; | |
// Little helper function for convenience | |
const getFetchOptions = (method, data) => ({ | |
method: method, | |
headers: { "Content-Type": "application/json" }, | |
body: JSON.stringify(data) | |
}) | |
// Get all the todos with GET | |
export const getTodos = async () => { | |
try { | |
const resp = await fetch(TODO_ENDPOINT); | |
return await resp.json(); | |
} | |
catch(e) { | |
console.log(e); | |
return null; | |
} | |
} | |
// Create a todo with POST | |
export const createTodo = async (todo) => { | |
try { | |
const resp = await fetch(TODO_ENDPOINT, getFetchOptions("POST", todo)) | |
return await resp.json(); | |
} | |
catch(e) { | |
console.log(e); | |
return null; | |
} | |
} | |
// Update a todo with PUT | |
export const updateTodo = async (todo) => { | |
try { | |
const resp = await fetch(TODO_ENDPOINT + "/" + todo._id, getFetchOptions("PUT", { text: todo.text })); // stripping out the id | |
return resp; | |
} | |
catch(e) { | |
console.log(e); | |
return null; | |
} | |
} | |
// Delete a todo with DELETE | |
export const deleteTodo = async (todo) => { | |
try { | |
const resp = await fetch(TODO_ENDPOINT + "/" + todo._id, { method: "DELETE" }) | |
return resp; | |
} | |
catch(e) { | |
console.log(e); | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment