I need to increment quantity of item in cart if item already exists in the state array. In the reducer I got it to work but it needs to be immutable. Because of this, my component doesnt update properly.
This is the code for my reducer:
import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/types';
const initialState = [];
//Cannot mutate array in reducer
export default function(state = initialState, action){
const { type, payload } = action;
switch(type){
case ADD_TO_CART:
const newState = [...state]
for(var i = 0; i < newState.length; i++){
if(newState[i].item.uid === payload.item.uid){
newState[i].item.qty ++;
return [...newState];
}
}
return [...state, payload];
case REMOVE_FROM_CART:
for(var j = 0; j < state.length; j++){
if(state[j].item.uid === payload.uid){
state[j].item.qty = 1;
}
}
return state.filter(cartItem => cartItem.item.uid !== payload.uid);
default:
return state;
}
}
I need to increment qty if item is already in the array.