Uncaught TypeError: Cannot read properties of undefined (reading 'reduce')

1.2k Views Asked by At

I am trying to update a counter with clicking on a add button so I am passing the data though cart context and reading it to update my counter but the app is keep giving me the undefined error for "reduce"

so this is the code:

const HeaderCartButton = (props) => {
  const cartCtx = useContext(CartContext);

  const numberOfCartItems = cartCtx.items.reduce((curNumber, item) => {
    
    return curNumber + item.amount;
    
  }, 0);

  return (
    <button className={classes.button} onClick={props.onClick}>
      <span className={classes.icon}>
        <CartIcon />
      </span>
      <span>Your Order</span>
      <span className={classes.badge}>{numberOfCartItems}</span>
    </button>
  );
};

so I believe it cannot read variables from "CartContext" and this is CartContext:

const CartContext = React.createContext({
  items: [],
  totalAmount: 0,
  addItem: (item) => {},
  removeItem: (id) => {},
});```



I dont think the problem would be with the React.createContext
2

There are 2 best solutions below

0
Canberk Koç On
const numberOfCartItems = cartCtx?.items?.reduce((curNumber, item) => {

return curNumber + item.amount; }, 0);

If you use it with Optional chaining, you can perform the operation after the data arrives. I think this usage will solve the problem.

0
Mulualem M On

You should check 'items' in your CartProvider should be the same as you have used in the reducer

const CartProvider=props=>{
    const addItemCartHandler=item=>{

    };
    const removeItemFromCartHandler=id=>{
       
    }
    const cartContext={
        items:[],
        totalAmount:0,
        addItem: addItemCartHandler,
        removeItem: removeItemFromCartHandler,
    };
    return <CartContext.Provider value={cartContext}>
              {props.children}
    </CartContext.Provider >
}