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

268
Vistas
Why setState() isn't working in React in my case?

I'm trying to implement a shopping cart by using contexts. The context works fine, but I need to create a method that removes one product each click. To do that I have to use useState() function. However, it doesn't even change the data in the state.

Here is my code for the function. Let me know if something isn't clear

For more info. productsToPurchase is an array that have all the purchased products which looks like that:

[{itemId: "ps-5", qty:2},{itemId: "iphone-xr", qty:4},{itemId:"ps-4", qty:7}]

export const CartContext = createContext()

class CartContextProvider extends Component {

    state = {
        productsToPurchase: [],
        totalPrice:[]
    }

    addProduct = (itemId, prices) => {
        this.setState(oldState => {
            const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
            return {
                productsToPurchase: !objWithIdExist
                    ? [...oldState.productsToPurchase, { itemId, qty: 1, price: prices }]
                    : oldState.productsToPurchase.map((o) =>
                        o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
                    )
            }
        })

        this.setState(oldState=>{
            return{
                totalPrice: getTotalAmount(oldState.productsToPurchase)
            }
        })
    }

    decreaseProduct = (itemId) =>{

        this.setState(oldState=>{

            // catch the item by mapping
            return oldState.productsToPurchase.map(product=>{
                if (product.itemId === itemId){
                    if (product.qty === 1){
                        //remove the product from the list
                        console.log("qty is 1!")
                    }
                    else {
                        console.log("Quantity is more than 1")
                        return  {...product, qty: product.qty - 1}
                    }
                }
            })

        })

    }

    render() {
        return (
            <CartContext.Provider value={{...this.state, addProduct: this.addProduct, decreaseProduct: this.decreaseProduct}}>
                {this.props.children}
            </CartContext.Provider>
        )
    }
}

function getTotalAmount(productsToPurchase) {

    const totalPrice = []

    productsToPurchase.map((product, productIndex) =>{
        product.price.map((price, priceIndex)=>{
            if (productIndex === 0){
                totalPrice.push({currency: price.currency, amount: price.amount * product.qty})
            }
            else {
                totalPrice.map(total=>{
                    if (total.currency === price.currency){
                        total.amount = total.amount + (price.amount * product.qty)
                    }
                })
            }
        })
    })

    return totalPrice
}

export default CartContextProvider;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want to subtract 1 from the selected product quantity and remove it if it hits 0, try this

// Make sure you return the new state object in its entirety
this.setState(({ productsToPurchase, ...oldState }) => ({
  ...oldState,
  productsToPurchase: productsToPurchase.reduce((arr, product) => {
    // is this the selected product?
    if (product.itemId === itemId) {
      // product qty > 1, include it with decrement
      if (product.qty > 1) {
        return [...arr, {
          ...product,
          qty: product.qty - 1
        }]
      }
      return arr // otherwise exclude this product
    }
    // otherwise, just include this product
    return [...arr, product]
  }, [])
}))
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