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,
Let's take a look at your reducer first.
if(action.type === ADD_TO_CART) {
// Land on a new state
// Refine the new state
// Return it
}
}
You need to take your time to do the above three steps, the reason why it's not working is you did too fast :)
const newState = {
...state, cartItems.action.payload
}
newState.total = newState.cartItems.reduce((acc,val) =>{
acc += val.count;
return acc
},0)
return newState
}
Doesn't matter how you do it, focus on the newState not state. It does seem everything can be done in one step, but there's order of things you need to pay attention to.
Don't use dispatch for calculated values.
Instead, create a helper function for calculation logic:
const getCartTotal = ({cartItems}) => {
return cartItems.reduce((acc,val) =>{
acc += val.count;
return acc;
}
};
In component:
const cart = useSelector(state => state.cart);
const total = getCartTotal(cart);
<Link to="/cart">
<Badge badgeContent={total} color="primary">
<ShoppingCartOutlined />
</Badge>
</Link>
You can create selectors for cart and cart total:
import {createSelector} from 'reselect';
// if you're already using @reduxjs/toolkit:
// import {createSelector} from '@reduxjs/toolkit';
const cartSelector = (state) => state.cart;
const cartTotalSelector = createSelector(
cartSelector,
state => getCartTotal(state);
);
In component:
const total = useSelector(cartTotalSelector);
As best practice the store shouldn't calculate anything but rather infer the next state from the current and combine them as needed via the action payload.
import { ADD_TO_CART, EMPTY_CART, REMOVE_FROM_CART } from '../actions/types';
const initialState = {
cart: [],
count: 0,
}
export default function(state=initialState, action) {
switch(action.type){
case ADD_TO_CART:
return {
...state,
cart: [action.payload, ...state.cart],
count: state.count + 1
}
case EMPTY_CART:
return {
...state,
cart: [],
count: 0
}
case REMOVE_FROM_CART:
return {
...state,
cart: state.cart.filter((item, i) => i !== action.payload.index),
count: state.count - 1
}
default:
return state
}
}