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

103
Visualizações
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 Respostas
Responde à pergunta

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 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