-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
78 lines (68 loc) · 2.26 KB
/
app.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
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js";
import {
getFirestore,
collection,
getDocs,
addDoc,
doc,
deleteDoc,
} from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration. Can be found in the Project Settings > General > Your Apps
const firebaseConfig = {
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Create an li element for the task
function loadElement(doc) {
var li = document.createElement("li");
li.setAttribute("data-id", doc.id);
var inputValue = doc.data().task;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("myUL").appendChild(li);
}
//get the list of tasks and render it
const querySnapshot = await getDocs(collection(db, "tasks"));
querySnapshot.forEach((doc) => {
loadElement(doc);
});
//pass the task that the user entered in the form to the database
const newTaskForm = document.getElementById("addingTask");
newTaskForm.addEventListener("submit", (e) => {
e.preventDefault();
addData(newTaskForm.newTask.value);
});
//add the user's new task to their todo list
async function addData(newTask) {
try {
const docRef = await addDoc(collection(db, "tasks"), {
task: newTask,
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to delete it from the database
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = async function () {
var taskId = this.parentElement.getAttribute("data-id");
await deleteDoc(doc(db, "tasks", taskId));
};
}