Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda