Search code examples
reactjsredux-toolkitshopping-cart

Uncaught TypeError: Cannot read properties of undefined (reading 'push') for shopping cart project


I'm creating shooping cart that can add product to cart page. But when I click the add to cart button, there is an error "Uncaught TypeError: Cannot read properties of undefined (reading 'push')"

thees is my code

cartSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { toast } from "react-toastify";

const initialState = {
  cartItems: localStorage.getItem("cartItems") ? JSON.parse(localStorage.getItem("cartItems")) : [],
  cartTotalQuantity: 0,
  cartTotalAmount: 0,
};
const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart(state, action) {
      let itemIndex = state.cartItems.findIndex(
        (item) => item.id === action.payload.id
      );
      if (itemIndex >= 0) {
        state.cartItems[itemIndex].cartQuantity += 1;
        toast.info("added product to cart", { position: "top-center" });
      } else {
        const tempProduct = { ...action.payload, cartQuantity: 1 };
        state.itemIndex.push(tempProduct);
        toast.success("succes to add product", { position: "top-center" });
      }
      localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
    },
  },
});

export const { addToCart } = cartSlice.actions;
export default cartSlice.reducer;

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import { productsApi } from "./redux/productsAPI";
import productsReducer from "./redux/productSlice";
import cartReducer from "./redux/cartSlice";

const store = configureStore({
  reducer: {
    products: productsReducer,
    cart: cartReducer,
    [productsApi.reducerPath]: productsApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(productsApi.middleware),
});
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

Home.jsx

import React from "react";
import { useGetAllProductsQuery } from "../redux/productsAPI";
import { useNavigate } from "react-router";
import { useDispatch } from "react-redux";
import { addToCart } from "../redux/cartSlice";

const Home = () => {
  const { data, error, isLoading } = useGetAllProductsQuery();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const handleAddToCart = (product) => {
    dispatch(addToCart(product));
    navigate("/cart");
  };
  return (
    <section className="px-4 py-12 w-full h-full flex flex-col items-center justify-center mt-10">
      {isLoading ? (
        <p className="duration-500">Loading...</p>
      ) : error ? (
        <p>Oh no, there was an</p>
      ) : (
        <>
          <h2 className="font-bold text-2xl md:text-4xl mb-8">Products</h2>
          <div className="grid grid-cols-2 lg:grid-cols-3 gap-6">
            {data?.map((item) => (
              <div
                key={item.id}
                className="flex flex-col items-center justify-center p-2 shadow-lg border border-gray-300"
              >
                <h3 className="mb-2 font-bold">{item.name}</h3>
                <div className="w-full h-[250px] md:h-[350px]">
                  <img
                    className="w-full h-full object-contain"
                    src={item.image}
                    alt={item.name}
                  />
                </div>
                <div className="w-full flex flex-col gap-3">
                  <div className="md:mt-4">
                    <p className="p-1 text-xs md:text-sm text-gray-600 font-bold">
                      {item.description}
                    </p>
                    <p className="p-1 font-bold">${item.price}</p>
                  </div>
                  <button
                    onClick={()=>handleAddToCart(item)}
                    className="w-full bg-red-600 text-white rounded-xl py-1 hover:bg-red-500"
                  >
                    Add to cart
                  </button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}
    </section>
  );
};

export default Home;

I've search the problem solving but I can't get through this problem. Thankyou for your help guys :) enter image description here


Solution

  • because of a typo in the addToCart reducer. You are trying to push an object into an undefined variable named "state.itemIndex", but it should be "state.cartItems"

    reducers: {
      addToCart(state, action) {
        let itemIndex = state.cartItems.findIndex(
          (item) => item.id === action.payload.id
        );
        if (itemIndex >= 0) {
          state.cartItems[itemIndex].cartQuantity += 1;
          toast.info("added product to cart", { position: "top-center" });
        } else {
          const tempProduct = { ...action.payload, cartQuantity: 1 };
          state.cartItems.push(tempProduct);
          toast.success("success to add product", { position: "top-center" });
        }
        localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
      },
    },