diff --git a/src/main/resources/static/js/pages/index/index.js b/src/main/resources/static/js/pages/index/index.js index a3e0dd9..efb6ae3 100644 --- a/src/main/resources/static/js/pages/index/index.js +++ b/src/main/resources/static/js/pages/index/index.js @@ -1,20 +1,14 @@ -import { showError, initErrors } from "../../shared/error.js"; +import { initErrors } from "../../shared/error.js"; +import { handleResponse } from "../../shared/helper.js"; +import { abortEditing } from "../../shared/sharedUI.js"; import * as api from "./api/indexAPI.js"; import * as ui from "./frontend/indexUI.js" const addListForm = document.querySelector(".addListForm"); async function addList(listName) { - const response = await api.addList(listName); - const json = await response.json(); - - if (!response.ok) { - console.error(`error creating list ${json.msg}`); - showError(json.msg); - return; - } - - ui.addList(json); + const json = await handleResponse(api.addList(listName), `error creating list`); + if (json) ui.addList(json); } function editList(listLi) { @@ -26,51 +20,27 @@ function editList(listLi) { formElement.querySelector(".editForm__name").focus(); - async function save() { - let formData = Object.fromEntries(new FormData(formElement)); - - console.log(`editing catogory ${id} with ${formData}`) - const response = await api.editList(id, { newListName: formData.newListName }); - - if (!response.ok) { - const json = await response.json(); - console.error(`error editing list ${json}`); - showError(json.msg); - - return; - } - - ui.editList(id, formElement, formData, listLi); - } - - formElement.addEventListener("submit", (event) => { + formElement.addEventListener("submit", async (event) => { event.preventDefault(); - save(); + + let formData = Object.fromEntries(new FormData(formElement)); + const result = await handleResponse(api.editList(id, { newListName: formData.newListName }), `error editing list`); + if (result) ui.editList(id, formElement, formData, listLi); }); formElement.querySelector(".editForm__abortButton").addEventListener("click", () => { - formElement.replaceWith(listLi); + abortEditing(formElement, listLi); }) formElement.addEventListener("keydown", (e) => { - if (e.key == "Escape") formElement.replaceWith(listLi); + if (e.key == "Escape") abortEditing(formElement, listLi); }) } async function deleteList(listElement) { - - const response = await api.deleteList(listElement.dataset.id); - - if (!response.ok) { - const json = await response.json(); - console.error(`error deleting list ${json}`); - showError(json.msg); - - return; - } - - ui.deleteList(listElement); + const json = await handleResponse(api.deleteList(listElement.dataset.id), `error deleting list`); + if (json) ui.deleteList(listElement); }