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

105
Vistas
Filter Inside UseEffect React Not Working

Im using the .filter() method on an object inside of a useEffect() method to filter out certain arrays out by name if they exist in a second object. I need to get the difference of arrays back into a useState() method. Im using the following and works outside the useEffect() method:

useEffect(() => {
  getDBData().then( (r) => { setAnotherObj(r); });
  getAPICall().then((r) => {
    let result = r.filter(
      (o1) => !anotherObj.filter((o2) => o1.name === o2.name)
    );
    setOption(result);
  });
}, []);

Now that works outside of the useEffect method when I add it to an event like onClick, but not inside, it might work one time then it doesn't at all. What am I missing about the useEffect method that I need to know why the filtering isn't being done?

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

0

Replace second filter with find. !anotherObj.filter(o2 => o1.name === o2.name) will always return false, be it has elements or not.

There is no dependency array in the in the useEffect, so whenever there is a state change, this useEffect gets triggered again.

Finding A-B, filter all the elements of A that are not in B. r.filter(o1 => anotherObj.find(o2 => o1.name !== o2.name)); With this it removes all the elements that are common in A and B. And leaves out only elements in A.

Update as follows,

useEffect( () => { 
  getAPICall().then( (r) => { 
   const result = r.filter(o1 => anotherObj.find(o2 => o1.name !== o2.name));         
    setOption(result);  
  });
}, []);
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