-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.js
89 lines (70 loc) · 2.31 KB
/
firebase.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
85
86
87
88
89
var config = {
apiKey: "AIzaSyB5gBoIMUbaDn2Glw-s5SRuTFoZ3zhz8AQ",
authDomain: "form-91821.firebaseapp.com",
databaseURL: "https://form-91821-default-rtdb.firebaseio.com",
projectId: "form-91821",
storageBucket: "form-91821.appspot.com",
messagingSenderId: "908992252495",
appId: "1:908992252495:web:b331a9f3f4f0dc1f14f83a",
measurementId: "G-LSYVY3HSKV"
};
firebase.initializeApp(config);
var db = firebase.database();
// CREATE REWIEW
var reviewForm = document.getElementById('reviewForm');
var fullName = document.getElementById('fullName');
var message = document.getElementById('message');
var hiddenId = document.getElementById('hiddenId');
reviewForm.addEventListener('submit', (e) => {
e.preventDefault();
if (!fullName.value || !message.value) return null
var id = hiddenId.value || Date.now()
db.ref('reviews/' + id).set({
fullName: fullName.value,
message: message.value
});
fullName.value = '';
message.value = '';
hiddenId.value = '';
});
// READ REVEIWS
var reviews = document.getElementById('reviews');
console.log(reviews);
var reviewsRef = db.ref('/reviews');
reviewsRef.on('child_added', (data) => {
var li = document.createElement('li')
li.id = data.key;
li.innerHTML = reviewTemplate(data.val())
reviews.appendChild(li);
});
console.log(reviews);
reviewsRef.on('child_changed', (data) => {
var reviewNode = document.getElementById(data.key);
reviewNode.innerHTML = reviewTemplate(data.val());
});
reviewsRef.on('child_removed', (data) => {
var reviewNode = document.getElementById(data.key);
reviewNode.parentNode.removeChild(reviewNode);
});
reviews.addEventListener('click', (e) => {
var reviewNode = e.target.parentNode
// UPDATE REVEIW
if (e.target.classList.contains('edit')) {
fullName.value = reviewNode.querySelector('.fullName').innerText;
message.value = reviewNode.querySelector('.message').innerText;
hiddenId.value = reviewNode.id;
}
// DELETE REVEIW
if (e.target.classList.contains('delete')) {
var id = reviewNode.id;
db.ref('reviews/' + id).remove();
}
});
function reviewTemplate({fullName, message}) {
return `
<div class='fullName'>${fullName}</div>
<div class='message'>${message}</div>
<button class='delete'>Delete</button>
<button class='edit'>Edit</button>
`
};