Quiero acceder al valor devuelto por una función externa dentro de la propiedad de fetch. El valor se está desconectando, pero necesito obtener el valor dentro de la propiedad 'título'. Disculpe si es una pregunta irrelevante, soy nuevo en esto. Necesito una solución o una alternativa por favor.
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)); } })Veo un par de problemas:
filter , por lo que return item.innerHTML; no hace nada: el valor devuelto se coloca en la matriz que nunca usa. (Las funciones tradicionales nunca hacen un return implícito, y no hay return en su función filterID , solo la devolución de llamada del filter ).editTodo .todoID y usa su HTML innerHTML en la llamada de búsqueda. Si es así, sería una operación de find en lugar de una operación de filter .Ver comentarios:
button.addEventListener("click", (e) => { // Where is `editTodo` used?? function editTodo(e) { // `todoItem` really should be plural if it"sa 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)); } }); O con un bucle for-of en todoItem ya que tanto NodeList (de querySelectorAll ) como HTMLCollection (de los métodos getElementsByXYZ ) son iterables (como lo son las matrices):
button.addEventListener("click", (e) => { // Where is `editTodo` used?? function editTodo(e) { // `todoItem` really should be plural if it"sa 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... } });