Em1n3m
Em1n3m

Reputation: 23

state.cartItems is not iterable when i want to add a item to cart

I'm trying to learn mern stack and redux by making a small e-commerce website and i have this state.cartItmes is not iterable error in redux action and i have no idea what is causing it or how to fix it

So because i hope one day i will became a Frontend developer i'm doing what a developer does...i'm asking you guys what i did wrong in my spagetti code

Cart Reducer

export const cartReducer = (state = { cartItems: [] }, action) => {
  if (action.type === "ADD_TO_CART") {
    return { cartItems: [...state.cartItems, action.payload] };
  }

  return state;
};

Cart Action

import axios from "axios";

export const addToCart = (id) => async (dispatch, getState) => {
  try {
    const { data } = await axios.get(`/products/${id}`);

    dispatch({ type: "ADD_TO_CART", payload: data });

    localStorage.setItem(
      "cartItems",
      JSON.stringify(getState().cart.cartItems)
    );
  } catch (error) {
    console.log(error.message);
  }
};

Cart component

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../actions/CartActions";
import { useParams } from "react-router-dom";

const Cart = () => {
  const dispatch = useDispatch();
  const { id } = useParams();

  const cart = useSelector((state) => state.cart);
  const { cartItems } = cart;
  console.log(cartItems);

  useEffect(() => {
    dispatch(addToCart(id));
  }, [dispatch, id]);

  return (
    <section>
      <div className="cart">
        <div className="cart-items">Cart</div>
        <div className="buy-items"></div>
      </div>
    </section>
  );
};

export default Cart;

Upvotes: 1

Views: 1376

Answers (1)

DaanKode
DaanKode

Reputation: 131

After analyzing your code, I think the issue may be the empty array that you initially set. You should try using some default value as initial value, I think this should solve the issue.

Also, it is generally not a good practice to put async logic inside a reducer. You may want to implement some middleware for this. Here's some more info on it: https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-middleware-to-enable-async-logic

Upvotes: 1

Related Questions