Reputation: 67
const API_URL = ` `;
const state = {
events: [],
};
const eventList = document.querySelector("#events");
const addEventForm = document.querySelector("#addEvent");
addEventForm.addEventListener("submit", addEvent);
/**
* Sync state with the API and rerender
*/
async function render() {
await getEvents();
renderEvents();
}
render();
async function getEvents() {
try {
const response = await fetch(API_URL);
const json = await response.json();
state.events = json.data;
} catch (error) {
console.error(error);
}
}
function renderEvents() {
if (!state.events.length) {
eventList.innerHTML = "<li>No events.</li>";
return;
}
const eventCards = state.events.map((event) => {
const li = document.createElement("li");
li.innerHTML = `
<h2>${event.name}</h2>
<p>${event.description}</p>
<p>${event.date}</p>
<p>${event.location}</p>
<button onClick = "deleteItem()">Delete</button>
`;
return li;
});
eventList.replaceChildren(...eventCards);
}
async function addEvent(event) {
event.preventDefault();
try {
const response = await fetch(API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: addEventForm.name.value,
description: addEventForm.description.value,
date: addEventForm.date.value,
location: addEventForm.location.value,
}),
});
if (!response.ok) {
throw new Error("Failed to create event!");
}
render();
} catch (error) {
console.error(error);
}
}
async function deleteItem() {
const deleted = await fetch(API_URL, {
method: "DELETE",
headers: {"Content-Type": "application/json"}
});
}
I am trying to create a "delete" button included in all my lists that will allow me to delete the listing on the HTML and API, but keep the rest of the items in the API and on screen.
I need to use the method "DELETE", but I am not sure how I need to be implementing it.
Here is the code to my HTML and CSS if needed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Party Planner</title>
<link rel="stylesheet" href="style.css" />
<script defer src="script.js"></script>
</head>
<body>
<h1>Events</h1>
<form id="addEvent">
<label>
Name
<input type="text" name="name" />
</label>
<label>
Description
<input type="text" name="description" />
</label>
<label>
Date/Time
<input type="text" name="date" />
</label>
<label>
Location
<input type="text" name="location" />
</label>
<button>Add Event</button>
</form>
<ul id="events"></ul>
</body>
</html>
ul {
display: flex;
flex-flow: row wrap;
list-style: none;
padding: 0;
}
li {
flex: 1 1 300px;
max-height: 200px;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
overflow: auto;
}
li img {
max-width: 100%;
max-height: 30%;
}
What can I try next?
Upvotes: 0
Views: 39