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

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

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