-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (63 loc) · 2.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const URL_BASE = "https://todolist-1af18-default-rtdb.firebaseio.com/";
const inputToDo = document.getElementById("textoToDo");
const listaToDo = document.getElementById("listaToDo");
const flechaExpandir = document.getElementById("flechaExpandir");
function clickExpandir(event) {
flechaExpandir.classList.toggle("rotate-arrow");
listaToDo.classList.toggle("expanded-list");
}
cargarDatosToDo();
async function submitFormulario(event){
event.preventDefault();
const textoToDo = inputToDo.value;
if (!textoToDo || textoToDo.trim().length == 0) {
alert("El texto no puede estar vacio")
return;
}
const resultado = await subirToDoAlServidor(textoToDo);
if (!resultado) {
alert("Hubo un error al guardar los datos");
return;
}
agregarEnLista(resultado);
}
async function cargarDatosToDo() {
const response = await fetch(URL_BASE + "to-do.json", {
method: "GET",
});
const datosServidor = await response.json();
for (let clave in datosServidor) {
const id = clave;
const texto = datosServidor[clave].texto;
const datosToDo = {id: id, texto: texto}
agregarEnLista(datosToDo);
}
}
function agregarEnLista(datosToDo) {
const textoBoton = `<button onclick="clickEliminar(event, '${datosToDo.id}')">Eliminar</button>`;
// Agregué un id al li para luego poder buscarlo
listaToDo.innerHTML += `<li id="${datosToDo.id}" class="to-do-items">${datosToDo.texto}${textoBoton}</li>`;
}
async function clickEliminar(event, id) {
// Hacer una petición al servidor para eliminar el dato
await fetch(URL_BASE + `to-do/${id}.json`, { method: "DELETE" });
// Eliminar el dato de la lista HTML
// Forma 1: usar el parentElement del target (el botón)
// El parent del botón debería ser el li
// const liEliminar = event.target.parentElement;
// Forma 2: ponerle un id al li para luego buscarlo
const liEliminar = document.getElementById(id);
listaToDo.removeChild(liEliminar);
}
async function subirToDoAlServidor(textoToDo) {
const datosEnviar = {
texto: textoToDo,
}
const response = await fetch(URL_BASE + "to-do.json", {
method: "POST",
body: JSON.stringify(datosEnviar),
});
const datosRespuesta = await response.json();
const id = datosRespuesta.name;
return { id: id, texto: textoToDo };
}