Runtime Error (TypeError): state.cartItems is undefined

I encountered an error while working on a MERN Stac tutorial while setting up the store. The error is in the following files:

  • store/cartSlice.js
  • components/productPage/infos/index.js

I would appreciate it if someone could help me solve the error.

Fenced code blocks in store/cartSlice.js:

import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  cartItems: [],
};

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart(state, action) {
      state.cartItems.push(action.payload);
    },
    updateCart(state, action) {
      state.cartItems = action.payload;
    },
    emptyCart(state, action) {
      state.cartItems = [];
    },
  },
});

export const { addToCart, updateCart, emptyCart } = cartSlice.actions;

export default cartSlice.reducer; 

Fenced code blocks in components/productPage/infos/index.js:

import styles from "./styles.module.scss";
import Rating from "@mui/material/Rating";
import { useState } from "react";
import { useRouter } from "next/router";
import Link from "next/Link";
import { TbPlus, TbMinus } from "react-icons/tb";
import { useEffect } from "react";
import { BsHandbagFill, BsHeart } from "react-icons/bs";
import Share from "./share";
import Accordian from "./Accordian";
import SimillarSwiper from "./SimillarSwiper";
import axios from "axios";
import DialogModal from "../../dialogModal";
import { useDispatch, useSelector } from "react-redux";
import { addToCart, updateCart } from "../../../store/cartSlice";
import { hideDialog, showDialog } from "../../../store/DialogSlice";
export default function Infos({ product, setActiveImg }) {
  const router = useRouter();
  const dispatch = useDispatch();
  const { data: session } = useSession();
  const [size, setSize] = useState(router.query.size);
  const [qty, setQty] = useState(1);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const { cart } = useSelector((state) => ({ ...state }));

  useEffect(() => {
    dispatch(hideDialog());
  }, []);
  useEffect(() => {
    setSize("");
    setQty(1);
  }, [router.query.style]);
  useEffect(() => {
    if (qty > product.quantity) {
      setQty(product.quantity);
    }
  }, [router.query.size]);
  const addToCartHandler = async () => {
    if (!router.query.size) {
      setError("Please Select a size");
      return;
    }
    const { data } = await axios.get(
      `/api/product/${product._id}?style=${product.style}&size=${router.query.size}`
    );
    if (qty > data.quantity) {
      setError(
        "The Quantity you have choosed is more than in stock. Try and lower the Qty"
      );
    } else if (data.quantity < 1) {
      setError("This Product is out of stock.");
      return;
    } else {
      let _uid = `${data._id}_${product.style}_${router.query.size}`;
      let exist = cart.cartItems.find((p) => p._uid === _uid);
      if (exist) {
        let newCart = cart.cartItems.map((p) => {
          if (p._uid == exist._uid) {
            return { ...p, qty: qty };
          }
          return p;
        });
        dispatch(updateCart(newCart));
      } else {
        dispatch(
          addToCart({
            ...data,
            qty,
            size: data.size,
            _uid,
          })
        );
      }
    }
  };

I encountered an error while working on a MERN Stac tutorial while setting up the store. The error is in the following files:

  • store/cartSlice.js
  • components/productPage/infos/index.js

I would appreciate it if someone could help me solve the error.

Without knowing the specific error message, it is difficult to provide a direct answer. However, based on the code provided, there are a few potential issues that may be causing the error.

In store/cartSlice.js:

  1. Make sure you have imported createSlice from “@reduxjs/toolkit” correctly.
  2. Check if action.payload is defined before pushing it to state.cartItems.

In components/productPage/infos/index.js:

  1. Make sure you have imported all the necessary modules correctly, such as “react”, “next/router”, “next/Link”, etc.
  2. Check if you have imported the correct icons from “react-icons”.
  3. Verify if all the dependencies are properly installed by running npm install or yarn install.
  4. Ensure that the useSelector hook is correctly connected to the Redux store.
  5. Check if the cart property is defined in the Redux state.

Please provide the specific error message or any additional information for a more accurate solution.