while working on an e-commerce app I need to calculate the total items in the cart. Cart is saved in the redux store, and the count state is also there to count the items.
I have tried different solutions like:
1)Reducing the state.cart in the Cart Reducer. But this was not working fine as I tried to reduce the state.cart on every add or remove item from the state.cart And it is not taking the immediate state.cart value, hence not deleting the items correspondingly.As following
if(action.type === ADD_TO_CART) {
return {
...state,
cartItems: action.payload,
total : state.cartItems.reduce((acc,val) =>{
acc += val.count;
return acc
},0)
}
}
else if(action.type === REMOVE_FROM_CART){
return {
...state,
cartItems: action.payload,
total : state.cartItems.reduce((acc,val) =>{
acc += val.count;
return acc
},0)
}
}
2)Second I create an action creator getTotal() and dispatched it from the useEffect hook. It's working totally fine but the only problem which I think is major one, console is giving max depth call stack error.As
Action.js file
export const getTotal = () => dispatch =>{
return dispatch({type: GET_TOTAL})
}
reducer.js file
else if(action.type === GET_TOTAL){
return {
...state,
total: state.cartItems.reduce((acc,val) =>{
acc += val.count;
return acc
},0)
}
}
Navbar.js file
useEffect(() =>{
dispatch(getTotal())
})
// -------
<Link to="/cart">
<Badge badgeContent={total} color="primary">
<ShoppingCartOutlined />
</Badge>
</Link>
So What is the best way to calculate the total items in the cart or if somehow can I handle the useEffect hook to avoid the call stack error?
Looking forward :) thanks,