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

198
Vistas
How to check if item already exists in your shopping cart - UseReducer React JS

I had this problem where i needed to make it so that an item can't be added twice in my shopping cart, then I searched this platform to see if there were any answers. I found out the question was asked Check if item already exists in cart when adding REACT but there were no sufficient contributions on it. Eventually i got the problem solved on my own but i wasn't allowed to contribute in the comments(I'm new here). So i decided to leave this here incase some one needs same.

I use context API and useReducer. Here is was my code

    switch (action.type) {
        case ADD_T0_CART:
        
        return {
                
                ...state, basket: [...state.basket, action.payload]
            }
            ```

After some hours of headache i eventually fixed it using a simple JS find() function.

  ```  export const commerceReducer = (state,action) => {
        switch (action.type) {
            case ADD_T0_CART:
                const itemExists = state.basket.find(
                    (item) => item.id === action.payload.id 
                )
                console.log(itemExists)
              
                if (!itemExists) return {
                    
                    ...state, basket: [...state.basket, action.payload]
                }
            ```
Hope someone finds this helpful.
about 4 years ago · Juan Pablo Isaza
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