React native add to cart quantity and total price issue
React native add to cart quantity and total price issue
Facing an issue where my cart is not updating the quantity and total price correctly after 2 quantities.
Using redux action during my ADD_TO_CART on press button, I will assign a new element into object of quantity:1
export function addToCart(card)
return (dispatch) =>
card.quantity = 1;
dispatch(type: ADD_TO_CART, data:card);
console.log(card);
;
On my reducer, here is the function
let cartState = data: , totalPrice: 0 ;
const cartReducer = (state = cartState, action) =>
switch (action.type)
case ADD_TO_CART:
let totalPriceCart = 0;
let checkforDuplicate = state.data.some(function (a)
if(a.sno === action.data.sno)
return true;
);
if(checkforDuplicate)
for (let i in state.data)
if (state.data[i].sno === action.data.sno)
state.data[i].quantity = action.data.quantity+1;
break;
for(let e in state.data)
totalPriceCart = totalPriceCart + (state.data[e].price*state.data[e].quantity);
return data: state.data, totalPrice: totalPriceCart ;
let cloneArr = state.data.concat(action.data);
for(let i in cloneArr)
totalPriceCart = totalPriceCart+(cloneArr[i].price*cloneArr[i].quantity);
return ...state, data : cloneArr, totalPrice: totalPriceCart
default:
return state;
;
What am I doing here in the reducer is,
Else will concat the array
At the end, will count the total price of the whole item in state and pass it back to my cart to show the total based on the quantity*price
Issue is that, currently, my code only shows until 2x, when adding the same item for 3rd time, the quantity will stay at 2x and the price is not calculating correctly.
1 Answer
1
you should mutate quantity of the state.data
if (checkforDuplicate)
for (let i in state.data)
if (state.data[i].sno === action.data.sno)
state.data[i].quantity = state.data.quantity + 1;
break;
for (let e in state.data)
totalPriceCart = totalPriceCart + (state.data[e].price * state.data[e].quantity);
return data: state.data, totalPrice: totalPriceCart ;
mutate using ==== Array.map()=======
let mutatedArr = state.data.map((item)=>
if (item.sno === action.data.sno)
item.quantity += 1;
return item;
);
let totalPriceCart = 0;
mutatedArr.forEach((item)=>
totalPriceCart+ = (item.price * item.quantity)
)
return data: mutatedArr, totalPrice: totalPriceCart ;
try to mutate array using map() function
– mahmoud mortda
Aug 22 at 17:52
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
i am getting quantity and price as NaN after 2nd time adding the same item
– user1897151
Aug 22 at 13:54