-
Notifications
You must be signed in to change notification settings - Fork 0
/
messages.js
63 lines (55 loc) · 2.04 KB
/
messages.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
const deleteMessage = async (messageId, authToken) => {
showLoading();
try {
const res = await axios({
method: "DELETE",
url: `https://mybrandbackend-93l8.onrender.com/api/messages/${messageId}`,
headers: { Authorization: `Bearer ${authToken}` },
});
hideLoading();
const row = document.querySelector(`a[data-messageid="${messageId}"]`).closest('tr')
if(row){
row.remove();
}
} catch (error) {
console.error("Error deleting message:", error);
}
};
const fetchMessages = async () => {
showLoading();
const authtoken = localStorage.getItem("jwt");
try {
const res = await axios({
method: "GET",
url: "https://mybrandbackend-93l8.onrender.com/api/messages",
headers: { Authorization: `Bearer ${authtoken}` },
});
console.log(res);
if (res.status === 200) {
hideLoading();
const messages = res.data.data.messages;
console.log(res.data.data.messages);
const tbody = document.getElementById("message-content");
tbody.innerHTML = ""; // Clear previous data
messages.forEach((message, index) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${index + 1}</td>
<td>${message.firstname}</td>
<td>${message.message}</td>
<td><a href="#" class="btn deleteMessage" data-messageid="${message._id}">Delete</a></td>`;
tbody.appendChild(row);
});
const deleteButtons = document.querySelectorAll('.deleteMessage');
deleteButtons.forEach((button) => {
button.addEventListener("click", (event) => {
const messageId = event.target.getAttribute('data-messageid');
deleteMessage(messageId, authtoken);
});
});
}
} catch (error) {
console.error("Error fetching messages:", error);
}
};
fetchMessages()