1

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
Sam Momen
  • 11
  • 2
  • I cannot reproduce your issue with the code you provided. [Codesandbox](https://codesandbox.io/s/xenodochial-julien-9cc7ts?file=/src/App.js). Try to console.log your values before "reduce" code block. Also, information about how your [Context.Provider](https://reactjs.org/docs/context.html#contextprovider) is used and how the context itself is updated can help. – Sergey Sosunov Jan 13 '23 at 17:06

2 Answers2

0
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

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 >
}
 

Mulualem M
  • 51
  • 1
  • 1
  • 6