0

I have a React app, where i have this function being called after a click:

dispatch( {type: 'ADD_TO_CART', payload: { cartProduct: {...props, quantity: 1} }}) 

The types are:

interface ICartProduct extends IProduct { 
    quantity: number
}

interface ICartItem { 
    product: ICartProduct
}

export interface IProduct {
    id: number
    category: string
    description: string
    name: string
    brand: string
    price: number
    linkImg: string
}

export interface IState { 
    isCheckoutResume: boolean
    isAddress: boolean
    isPayment: boolean
    isSuccess: boolean
    isHomePage: boolean
    cart: Array<ICartProduct>
    products: Array<IProduct>
}

Inside the reducer function, i have this:

export const reducer = (state: IState, action: IAction): IState => { 

    switch (action.type){ 

        //other features

        case ('ADD_TO_CART'):
            if(action?.payload?.cartProduct) { 

                console.log(action.payload.cartProduct.quantity) // logs always 1, which is expected 
                console.log(action.payload.cartProduct) // logs always an objects having in the quantity property the double + 2 of the value that is already in the cart for that product, so in the second click for the same product it gives 4 (1*2 + 2), in the third click it is 10 (4*2 + 2)

I can't figure out what is happening, should not these lines logs the same value for quantity since it is the same javascript object?

This is not related to console logging only since the application state for cart is also carrying this behavior.

Thank you.

  • Please revise your post title to ask a clear, specific question. See [ask]. – isherwood Jun 13 '22 at 16:10
  • This is due to lazy loading the object in the console. The quantity changed between the `console.log()` and you clicking the drop-down arrow in the debugger. See: https://stackoverflow.com/q/4057440/12914833. You can use `console.log(action.payload.cartProduct.toString())` to avoid lazy loading. – Chris Hamilton Jun 15 '22 at 01:48

0 Answers0