diff --git a/apiutils.js b/apiutils.js new file mode 100644 index 0000000..9bf7488 --- /dev/null +++ b/apiutils.js @@ -0,0 +1,29 @@ +const apiUrl = "http://localhost:4730/todos"; + +/* FUNCTION - to get todos from the API*/ + +export function fetchData(path = "", options = {}) { + return fetch(apiUrl + path, options).then((response) => response.json()); +} + +export function postData(newTodo) { + const options = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(newTodo), + }; + return fetchData("", options); + //return fetch(apiUrl + path, options).then((response) => response.json()); +} +/* +export function deleteAllData(newTodo) { + Promise.all( + doneTodos.map((doneTodo) => + fetch(apiUrl + `/${doneTodo.id}`, { + method: "DELETE", + headers: { "Content-Type": "application/json" }, + }) + ) + ); +} + */ diff --git a/index.html b/index.html index 745d888..15d9f85 100644 --- a/index.html +++ b/index.html @@ -52,6 +52,6 @@

Getting things doneā€¦

- + diff --git a/script.js b/script.js index 4e54013..fb642a3 100644 --- a/script.js +++ b/script.js @@ -1,5 +1,7 @@ "use strict"; +import { fetchData, postData } from "./apiutils.js"; + /* State and initializing ========================================================================== */ @@ -8,8 +10,8 @@ const taskForm = document.getElementById("task-form"); const input = document.getElementById("input"); const taskList = document.getElementById("task-list"); const clearButton = document.getElementById("clear-btn"); -const apiUrl = "http://localhost:4730/todos"; - +/* const apiUrl = "http://localhost:4730/todos"; + */ // Modal Styling const corner = Swal.mixin({ @@ -58,8 +60,7 @@ function render() { /* FUNCTION - to get todos from the API ========================================================================== */ function getTodosFromApi() { - fetch(apiUrl) - .then((response) => response.json()) + fetchData() // Nochmal anschauen .then((todosFromApi) => { state.tasks = todosFromApi; render(); @@ -80,12 +81,7 @@ function saveTodoToApi() { const newTodoText = input.value.trim(); const newTodo = { description: newTodoText, done: false }; - fetch(apiUrl, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(newTodo), - }) - .then((response) => response.json()) + postData(newTodo) .then((newTodoFromApi) => { state.tasks.push(newTodoFromApi); render(); @@ -140,6 +136,7 @@ function removeDoneTodosFromApi() { const doneTodos = state.tasks.filter((task) => task.done); // Use Promise.all for multiple API requests and delete many completed todos + //Promise All Settled Promise.all( doneTodos.map((doneTodo) => fetch(apiUrl + `/${doneTodo.id}`, {