Pruteanu Alexandru
Pruteanu Alexandru

Reputation: 247

Add to cart React Native/Redux not working

I don't have much experience in terms of React Native, but I've been having a problem for a few days. So I want that when I click on the add button to the cart several times I can increase the quantity to the respective product.

actions/cart.js

export const addToCartValue = (item)=>{
return async (dispatch) => {
    try{
        
        dispatch({type:'ADD_TO_CART_PROD', payload: item})
       
    }catch(e){
        alert(e)
    }
  }
}

item is an object that has the following values

Object:{
   id:'44444',
   product:{img:'sssss',name:'sssss'},
   qty:1
}

In reducers the first time I did something like that:

const initialState = {
   cart: [],
   qtytotal: 0,

}
const cart = (state = initialState , action) =>{
  switch (action.type) {
    case 'ADD_TO_CART_PROD':
        return {
            ...state,
             cart: [action.payload, ...state.cart],
             qtytotal: state.qtytotal + action.payload.qty
        }
      default:
        return state
    }
}

but the end result was something like that:

arr=[
 {
   id:'4444',
   product:{img:'sssss',name:'sssss'},
   qty:1
 },
 {
   id:'4444',
   product:{img:'sssss',name:'sssss'},
   qty:1
 },,
 {
   id:'4444',
   product:{img:'sssss',name:'sssss'},
   qty:1
 },,
 {
   id:'4444',
   product:{img:'sssss',name:'sssss'},
   qty:1
 },
 {
   id:'5555',
   product:{img:'aaaaa',name:'aaaaa'},
   qty:6
 },
 qtytotal:10
]

this is not good because at any action of the user at the same btn or on the product page it generates a new object with values ​​often the same values.


I managed that through a series of filters and a lot of code in a way to separate the data into a final form something like:

finalData:[
  {
   id:'4444',
   product:{img:'sssss',name:'sssss'},
   qty:4
 },
 {
   id:'5555',
   product:{img:'aaaaa',name:'aaaaa'},
   qty:6
 },
 totalQty:10
]

the basket on the client side looks somewhat normal:

enter image description here

But when it comes to increasing or decreasing the amount in the basket, the real problems arise due to the fact that the data in redux is stored poorly, in fact I can't do anything.

In conclusion if I click 5 times on product x instead of creating 5 objects with the same value and after filtering over filters,i want to have a single object but with the quantity adjusted.

I tried to solve the problem by doing something like that:

const cart = (state = initialState , action) =>{

  switch (action.type) {
    case 'ADD_TO_CART_PROD':
        return {
            ...state,
              cart:state.cart.map(item =>
                item .id === action.payload.id 
                ? 
                 //find obj in redux with id increment update gty
                {...item, item.qty: item.qty + action.payload.qty} 

                : item,
              ),
     
            qtytotal: state.qtytotal + action.payload.qty
         }     
      default:
         return state
 }

}

I found this example and followed it:exemple add to cart redux

but nuy doesn't work at all, and in the console it shows me:

Array:[]

I only have 2 weeks since I started doing something in React Native, but I can't figure out how I could do this add to cart in which instead of creating another object to adapt the existing one.

has anyone ever been through this, is there a solution.

Upvotes: 0

Views: 875

Answers (1)

Mayukh Chakraborty
Mayukh Chakraborty

Reputation: 175

I got through your problem thoroughly and found out somethings:

  1. When Incrementing, Don't use Add to cart, but create another action type that will increment / decrement the cart. Let's me show you a very basic example:
const ADD_TO_CART = 'ADD_TO_CART'
const INCREMENT = 'INC'
const DECREMENT = 'DEC'

const InitialState = {
    cart: [],
    totalQty: 0
}

//how payload will look:
var payload = {
    _id: 0,
    product: {},
    qty: 0
}

const cart = (state = InitialState, action) => {
    switch(action.type)
    {
        case ADD_TO_CART:
            //check for duplicate data
            var duplicate = false
            const setDuplicate = (val) => {
                duplicate = val
            }
            state.cart.forEach(prev => {
                if (prev._id === action.payload._id)
                {
                    setDuplicate(true)
                }
            })

            if (duplicate) {
                return state
            } else {
                return {
                    ...state,
                    cart: [...state.cart, action.payload],
                    totalQty: state.totalQty + 1
                }
            }
        case INCREMENT:
            return {
                ...state,
                cart: state.cart.map(prev => {
                    if ( prev._id === action.payload._id )
                    {
                        return {
                            ...prev,
                            qty: prev.qty + 1
                        }
                    } else {
                        return prev
                    }
                })
            }

        case DECREMENT:
            return {
                ...state,
                cart: state.cart.map(prev => {
                    if ( prev._id === action.payload._id )
                    {
                        return {
                            ...prev,
                            qty: prev.qty - 1
                        }
                    } else {
                        return prev
                    }
                })
            }

        default:
            return state
    }
}

Upvotes: 1

Related Questions