Search code examples
reactjsreact-context

Reducer Dispatch Push Issue


Could someone look at my reducer to see what the issue is with .push()? For some reason the following error is being thrown

error TypeError: Cannot read properties of undefined (reading 'push')

but the value isn't undefined.

Cart Reducer State = {"cartItems":[],"itemCount":0,"total":0}
Cart Reducer Action = {"type":"ADD_ITEM","payload":{"_id":"61cb88d85f499fd4563e99d3","sku":1001,"image":"blueband","title":"Wrist Band - 1 Custom Insert","description":"Band with custom photo insert included with purchase.","active":{"status":true,"display":true,"startDate":"2021-09-21T22:55:03.686Z","endDate":""},"color":"Blue","quantity":100,"price":16.99,"createdAt":"2021-12-28T21:59:52.357Z","updatedAt":"2021-12-28T21:59:52.357Z","__v":0}}
export const sumItems = (cartItems) => {
  return {
    itemCount: cartItems.reduce((total, prod) => total + prod.quantity, 0),
    total: cartItems.reduce(
      (total, prod) => total + prod.price * prod.quantity,
      0
    ),
  };
};

const cartReducer = (state, action) => {
  switch (action.type) {
    case "ADD_ITEM":
      //check if item is in cart
      if (!state.cartItems.find((item) => item._id === action.payload._id)) {
        //Below is an Object
        console.log(JSON.stringify(state));
        console.log(JSON.stringify(action));
        state.cartItem.push({
          ...action.payload,
          quantity: 1,
        });
      }
      return {
        ...state,
        cartItems: [...state.cartItems],
        ...sumItems(state.cartItems),
      };
    default:
      return state;
  }
};

export default cartReducer;

Solution

  • You need to provide an initial state to your reducer. You’re currently returning state in the default case, which will be undefined initially (Check in redux-dev tools).

    In your reducer definition, set a default value to the state argument, Something like this state = {cartItems: [], itemCount: 0, total: 0}.

    or you could move the initial state in a file say state.js with the following content:

    export default {
      cartItems: [],
      itemCount: 0,
      total: 0
    }
    

    and then import this in your reducer:

    import initialState from './state';
    

    and set the initialState in your reducer via default value of argument or just return initalState from the default case:

    default: 
      return initialState;