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

359
Vistas
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 Respuestas
Responde la pregunta

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