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

180
Visualizações
Simple To-Do List with React, Array.filter is not working as expected?

I'm trying to make a function to delete the "clicked" task but I can't figure out what is the problem.

  1. I created an array with useState where I save all tasks.
  2. When task is created is asigned to a key ( i ).
  3. When delete button is clicked, trigger deleteTask function with ( i ) parameter.
  4. DeleteTask function expect a parameter which is the task key.
  5. A new variable is created where I do a filter to the array and ask for an array with all the values less the one with the specified key. Here is the problem the same array is returned and nothing is deleted because I'm setting the same array

Any idea what I'm doing wrong?

Thank you in advance!!

const { useState } = React;

function Todo() {

  const [item, setItem] = useState("");
  const [itemArray, setItemArray] = useState([]);

  function addItem() {
    setItemArray((prev) => {
      return [...prev, item];
    });
    setItem("");
  }

  function handleChange(event) {
    const { value } = event.target;
    setItem(value);
  }

  function deleteTask(key) {
    const newItemArray = itemArray.filter((task) => task.key != key);

    console.log(newItemArray);
    console.log(key);

    setItemArray(newItemArray);
  }

  return (
    <div className="container">
      <div className="heading">
        <h1>To-Do List</h1>
      </div>
      <div className="form">
        <input type="text" onChange={handleChange} value={item} />
        <button onClick={addItem}>Add</button>
      </div>
      <div>
        <ul>
          {itemArray.map((task, i) => {
            return (
              <li key={i}>
                {task}
                <button
                  key={i}
                  onClick={() => deleteTask(i)}
                  className="">Borrar
                </button>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );

}

ReactDOM.render(
  <Todo />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are looking for a key property when filtering your array on the deleteTask function. You should instead compare the selected task to the index of your current element.

const newItemArray = itemArray.filter((task, index) => index != key);

about 4 years ago · Juan Pablo Isaza Relatório

0

When you add item, you didn't set key to item and you just add string in state and when you want to filter items, your key is undefiend

In following line, task does not contain key property

const newItemArray = itemArray.filter((task) => task.key != key);

You need to store key in task.

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