Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

442
Visualizações
How to delete an item from a list using vanilla JavaScript?

I am trying to build a book directory using vanilla javascript and axios. What I want is that every time I press the delete button the book will be deleted from the list. But every time I press the button it shows an error. I don't know where is the problem.

My app.js file:

 const delBtn = [...document.querySelectorAll(".del-btn")];

  delBtn.map((button) => {
  button.addEventListener("click", async (e) => {
     e.preventDefault();
     const idValue =
        e.currentTarget.parentElement.firstElementChild.nextElementSibling
           .nextElementSibling.innerHTML;

     try {
        const res = await axios.delete(`/api/books/${Number(idValue)}`);

        const data = res.data.find((book) => book.id === Number(idValue));

        if (!data) {
           console.log(`No book with such${idValue}`);
        }
        const filteredBook = books.filter((book) => {
           if (book.id !== Number(idValue)) {
              const { title, author, image, desc, id } = book;
              return `
              <div class="card flex" style="width: 18rem; min-height:24rem;">
                    <img
                    src=${image}
                    class="card-img-top w-50 rounded mx-auto d-block"
                    alt="#"
                     />
                  <div class="card-body">
                 <h4 class="card-title">${title}</h4>
                 <h6>Written by: <span class="text-primary">${author}</span></h6>
                 <p>${id}</p>
               <p class="card-text"> ${desc}</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
        <a
           class="btn btn-danger del-btn"
           type="submit"
           ">Delete</a>
     </div>
     </div>  
        `;
           }
        });
        card.innerHTML = filteredBook;
     } catch (error) {
        console.log("Error");
     }
  });

My server.js file:

app.delete("/api/books/:id", (req, res) => {
const { id } = req.params;

const book = books.find((book) => book.id === Number(id));

 if (!book) {
   return res
     .status(400)
     .json({ success: false, msg: `No book with the id of ${id}` });
 }

 const newBook = books.filter((book) => book.id !== Number(id));
 return res.status(200).json({ success: true, data: newBook });
  });

app.listen(PORT, () => {
console.log("Server is running on port 5000...");
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It looks like this:

const data = res.data.find((book) => book.id === Number(idValue));

needs to be changed to:

const data = res.data.data.find((book) => book.id === Number(idValue));

res.data is the axios response data and then you have a data element in your response that you need to get. Your response is this:

return res.status(200).json({ success: true, data: newBook });

so, res.data from axios gets you this { success: true, data: newBook } so to get the newBook data, you need res.data.data.


FYI, all of this is basic debugging. You log your exact error, follow the hints it gives you, then log other intermediate values to see where things went wrong and usually you can then see where the error is.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda