So I have built an REST API with working endpoints GET, POST, PUT and DELETE on an Express server and currently working on the clientside. The Express server is reading and writing to a JSON-file. So on the clientside I've done a HTML and a scriptfile, I've managed to make a GET-request and render what's in the JSON-file so far on the HTML. Also I've managed to make a inputform on the HTML and make a POST-request that makes a new object with all keys/values I would like the object to have. So my thought was that to make a PUT-request and update a certain object. Is it possible to use the HTML attribute contenteditable? At the part where I'm rendering everything from the script-file I'm in a for of loop and also making a addEventListener where I'd like to send the NEW information from the contenteditable element to the async/await-function that is making the PUT-request. But at all tries I'm only able to see the old information.
async function printCharacters(){
const get = await fetch ('http://localhost:3000/api')
const characters = await get.json()
for(const character of characters){
const characterContainers = document.createElement("div");
main.appendChild(characterContainers);
characterContainers.className = "characterContainer";
const characterName = document.createElement("p");
characterName.setAttribute("contenteditable", "true");
characterName.innerHTML = character.characterName;
characterContainers.appendChild(characterName);
const updateButton = document.createElement("button");
updateButton.className = "updateButton";
updateButton.innerText = "Update";
characterContainers.appendChild(updateButton);
updateButton.addEventListener("click", () => {
updateCharacter(characterName.innerHTML);
});
}
}
async function updateCharacter(data){
const response = await fetch (`http://localhost:3000/api/update/${data.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"characterName": data.characterName
})
})
return response.json();
};
I've tried making outside a function and then it's possible to console.log and catch the new information.
updateButton.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const changedData = {
id: character.id,
characterName: characterName.innerHTML,
class: characterClass.innerHTML,
weapon: characterWeapon.innerHTML,
description: characterDescription.innerHTML
};
updateCharacter(changedData);
This was the working solution. I've tried before to get innerHTML
both inside and outside the eventListener
, but to get the updated information inside the element it has to be inside the eventListener
and also the addition of preventDefault
and stopPropagation
.