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

353
Visualizações
How to prevent adding duplicate objects into array in state in ReactJS?

I am fetching from an API that returns data in the form of an array. Lets say I have an array of 5 objects in this array which are exactly the same. I want to prevent duplicates by checking if duplicate exists before adding to my restaurants State. Below are snippets of my code:

const [restaurants, setRestaurants] = useState([])
const checkForDuplicateBusiness = (businessArray)=>{
    businessArray.forEach(singleBusiness=>{
      if(!restaurants.some(restaurant=> restaurant.id === singleBusiness.id)){
        setRestaurants(restaurants=>[...restaurants, singleBusiness])
        console.log(restaurants) //returns []
      }
    })
  }

The problem is that when I am checking with this line if(!restaurants.some(restaurant=> restaurant.id === singleBusiness.id)) the restaurants state is always empty. I understand that setState is async so the state is not updated by the time im checking it for the next iteration in the forEach loop. Im not sure what to do.

When I console log the restaurants via useEffect like:

useEffect(()=>{
  console.log(restaurants)
},[restaurants])

it will show 5 identical objects.

[
   0: {id: 'sDlYSTdgZCx0-3cRetKn8A'}
   1: {id: 'sDlYSTdgZCx0-3cRetKn8A'}
   2: {id: 'sDlYSTdgZCx0-3cRetKn8A'}
   3: {id: 'sDlYSTdgZCx0-3cRetKn8A'}
   4: {id: 'sDlYSTdgZCx0-3cRetKn8A'}
]

I am confused on this behavior because if i have exactly 5 copies of the object, that means my setRestaurants(restaurants=>[...restaurants, singleBusiness]) was working properly indicative from the spread operator. but my check if statement isnt?

The other solution I've thought of is to store my fetched data in a temporary array and perform the "preventDuplicate" logic in there, and then set it to my restaurants. But I'm not sure if this is the most efficient method. Is there a better way or the "React" way for this?

Any suggestions are appreciated. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The setStateSetter function gives you the updated state. Use it higher:

function uniqueById(items) {
  const set = new Set();
  return items.filter((item) => {
    const isDuplicate = set.has(item.id);
    set.add(item.id);
    return !isDuplicate;
  });
}

const updateRestaurantsUnique = (newItems) => {
  setRestaurants((restaurants) => {
    return uniqueById([...restaurants, ...newItems]);
  });
};

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