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

263
Vistas
Why filtering isn't working in React and JS. Help me to find a mistake

Can not understand why filter is not working. The function get an object. If there is the same object in the state, the function delete this object from the state. If not, add to the state. The problem is that the object rewrites the state, but not add it to the state.

For example, object {a: 1, b: 2}

const [products, setProducts] = useState<any[]>([]);

const addObject = (data) => {
    const sameData = !!products.find((item) => item.id === data.id);
    const deleteData = products.filter((item) => item.id !== data.id);
    const newData = sameData ? deleteData : [...products, data]; 
    return setCheckedRoles(newData);
  };

As a result I get not [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}]; but only one object that come to function [{a: 1, b: 2}]

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You want deleteData to run only when sameData is true, but instead it is running the moment you're defining it. (remember that filter() is being invoked)

To get the expected behaviour move the deleteData to be a function and execute it as per your wish

const [products, setProducts] = useState<any[]>([]);

const deleteData = (products) => products.filter((item) => item.id !== data.id);

const addObject = (data) => {
    const sameData = !!products.find((item) => item.id === data.id);
    const newData = sameData ? deleteData(products) : [...products, data]; 
    return setCheckedRoles(newData);
};

Also please find a better name for the function addObject :)

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