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

244
Visualizações
React - filter deletes all items instead of one

I fail to understand why .filter deletes all items instead of one even though the key should be unique. Why? I think it should filter out the id that is in the function, but it keeps deleting everything, because of the .map, right?

const App = () => {
  const [state, setState] = useState("")
  const [list, updateList] = useState([])

  const addItem = () => {
    list.push(state)
    setState('')
    updateList(list)
  }

  const removeItem = (id) => {
    updateList(list.filter((item) => item.id !== id));
  
  }

  return (
    <div>
        <input placeholder='type...' value={state} onChange={(e) => setState(e.target.value)}></input>
        <button onClick={addItem}>Submit</button>
      {list.map((item) => (
        <>
            <div key={item.id}>{item}</div>
            <button onClick={() => removeItem(item.id)}>delete</button>
            </>
        )
      )}
    </div>
  )
}

export default App
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You dont have item.id actually, you just have item which is a string. You add items to that array from the text box, so you only have Array of strings

What you should do is remove by item not item.id

your code should be something like that remoteItem function :

const removeItem = (selectedItem) => {
updateList(list.filter((item) => item !== selectedItem));

};

Then in your list.map

{list.map((item) => (
        <>
          <div key={item}>{item}</div>
          <button onClick={() => removeItem(item)}>delete</button>
        </>
      ))}
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