-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
60 lines (52 loc) · 1.67 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
const cafeList = document.querySelector('#cafe-list');
const form = document.querySelector("#add-cafe-form");
//create element and render cafe
function renderCafe(doc){
let li = document.createElement('li');
let name = document.createElement('span');
let city = document.createElement('span');
let cross=document.createElement('div');
li.setAttribute('data-id', doc.id);
name.textContent = doc.data().name;
city.textContent = doc.data().city;
cross.textContent = 'X';
li.appendChild(name);
li.appendChild(city);
li.appendChild(cross);
cafeList.appendChild(li);
//deleting data
cross.addEventListener('click', (e) => {
e.stopPropagation();
let id = e.target.parentElement.getAttribute('data-id');
db.collection('cafes').doc(id).delete();
})
}
//getting data from firebase where('city', '>', 'n')
//where('city', '==', 'New York').orderBy('city').
//db.collection('cafes').get().then((snapshot) => {
//// snapshot.docs.forEach(doc => {
// renderCafe(doc);
//});
//});
//saving data
form.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('cafes').add({
name: form.name.value,
city: form.city.value
});
form.name.value='';
form.city.value='';
});
//real-time listener
db.collection('cafes').orderBy('city').onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if(change.type == 'added'){
renderCafe(change.doc);
}else if(change.type == 'removed'){
let li = cafeList.querySelector('[data-id='+ change.doc.id+ ']');
cafeList.removeChild(li);
}
})
})