I want to access the value returned from an outer function inside the property of fetch. The value is being logged out but I need to get the value inside fetch in the 'title' property. Please excuse me if it is an irrelevant question, I am new to this. Need a solution or an alternative please.
button.addEventListener('click', (e) => {
function editTodo(e) {
function filterID() {
Array.from(todoItem).filter((item) => {
if (item.getAttribute('id') == todoID) {
console.log(item.innerHTML);
return item.innerHTML;
}
});
} //<<value is being logged out
fetch(`${url}/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: filterID(), //<<need to access here
}),
})
.then((res) => {
setMessage('Updated');
return res.json();
})
.catch((error) => console.log(error));
}
})
CodePudding user response:
I see a couple of issues:
- You aren't doing anything with the array that
filtercreates, so thereturn item.innerHTML;doesn't do anything — the value returned is put in the array you never use. (Traditional functions never do implicitreturn, and there's noreturnin yourfilterIDfunction, just thefiltercallback.) - You never call
editTodo. - It sounds from the comments like you have a collection/list of HTML elements and you're trying to find the one that matches
todoIDand use itsinnerHTMLin the fetch call. If so, that would be afindoperation rather than afilteroperation.
See comments:
button.addEventListener("click", (e) => {
// Where is `editTodo` used??
function editTodo(e) {
// `todoItem` really should be plural if it"s a collection/list/array
// Use `find` to find the matching `todo`, and then use `innerHTML` on it
const todo = Array.from(todoItem).find((item) => item.getAttribute("id") === todoID);
if (!todo) {
return; // Not found
}
fetch(`${url}/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: todo.innerHTML, // ***
}),
})
.then((res) => {
setMessage("Updated");
return res.json();
})
.catch((error) => console.log(error));
}
});
Or with a for-of loop on todoItem since both NodeList (from querySelectorAll) and HTMLCollection (from getElementsByXYZ methods) are iterable (like arrays are):
button.addEventListener("click", (e) => {
// Where is `editTodo` used??
function editTodo(e) {
// `todoItem` really should be plural if it"s a collection/list/array
// Use `find` to find the matching `todo`, and then use `innerHTML` on it
let todo = null;
for (const item of todoItem) {
if (item.getAttribute("id") === todoID) {
todo = item;
break;
}
}
if (!todo) {
return; // Not found
}
// ...same otherwise...
}
});
