Add delete student function

This commit is contained in:
Aleksey Filippov 2024-11-07 10:24:20 +04:00
parent 093aa2a390
commit b4647fe4e9

View File

@ -46,6 +46,7 @@
<th scope="col">E-Mail</th> <th scope="col">E-Mail</th>
<th scope="col">Phone</th> <th scope="col">Phone</th>
<th scope="col">Group</th> <th scope="col">Group</th>
<th scope="col"></th>
</tr> </tr>
</thead> </thead>
<tbody id="students"> <tbody id="students">
@ -56,11 +57,27 @@
Автор, 2022 Автор, 2022
</footer> </footer>
<script type="module"> <script type="module">
const deleteStudent = async (id) => {
// eslint-disable-next-line no-restricted-globals, no-alert
const answer = confirm(`Do you want to delete student with id = ${id}?`);
if (!answer) {
return;
}
const response = await fetch(`http://localhost:3001/students/${id}`, { method: "delete" });
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
};
const getStudents = async () => { const getStudents = async () => {
const students = document.getElementById("students"); const students = document.getElementById("students");
students.innerHTML = "";
const response = await fetch("http://localhost:3001/students?_expand=group"); const response = await fetch("http://localhost:3001/students?_expand=group");
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const data = await response.json(); const data = await response.json();
data.forEach(element => { data.forEach((element) => {
const createTd = (value) => { const createTd = (value) => {
const td = document.createElement("td"); const td = document.createElement("td");
td.innerText = value; td.innerText = value;
@ -78,6 +95,15 @@
container.appendChild(createTd(element.email)); container.appendChild(createTd(element.email));
container.appendChild(createTd(element.phone)); container.appendChild(createTd(element.phone));
container.appendChild(createTd(element.group.name)); container.appendChild(createTd(element.group.name));
const btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.classList.add("btn", "btn-danger");
btn.innerHTML = "Delete";
container.appendChild(btn);
btn.addEventListener("click", async () => {
await deleteStudent(element.id);
getStudents();
});
students.appendChild(container); students.appendChild(container);
}); });
console.log(data); console.log(data);