Home > Enterprise >  Reducer Dispatch Push Issue
Reducer Dispatch Push Issue

Time:01-14

Good Afternoon,

Could someone look at my reducer to see what it is throwing a fit on the .push()? For some reason I am throwing the following 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;

CodePudding user response:

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;

  •  Tags:  
  • Related