I'm working on react shopping cart using react-redux and My add to cart Functionality is not working. I've tried a lot with multiple approaches but those did not work. I'm unable to get data into my CartItem. Did stack over flow tried multiple things but still not worthy.
this is my CartActions.js
import React from "react";
import axios from "axios";
import { ADD_CART_ITEM } from "../constant/cartConstant";
const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/http://127.0.0.1:8000/products/${id}`);
console.log(data, "<<<<<<DATA");
dispatch({
type: ADD_CART_ITEM,
payload: {
product: data.id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
},
});
localStorage.setItem(
"cartItems",
JSON.stringify(getState().CartReducer.cartItems)
);
};
export default addToCart;
this is my Cart.js
import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux'
import addToCart from '../actions/CartActions'
function Cart() {
const { id } = useParams();
const { search } = useLocation();
const ProductID = id;
const qty = search ? search.split("=") : 1
console.log(qty, ">>>QTY");
const dispatch = useDispatch()
console.log(ProductID, ">>>>PROduct ID");
useEffect(() => {
if (ProductID) {
dispatch(addToCart(ProductID, qty))
}
console.log("Hello world");
}, [dispatch, ProductID, qty])
return (
<div>Cart</div>
)
}
export default Cart
this is my CartReducer.js
import React from "react";
import { ADD_CART_ITEM } from "../constant/cartConstant";
function cartReducer(state = { cartItems: [] }, actions) {
switch (actions.type) {
case ADD_CART_ITEM:
const Item = actions.payload;
const exitsItem = state.cartItems((x) => x.product === Item.product);
if (exitsItem) {
return {
...state,
cartItems: state.cartItems.map((x) =>
x.product === exitsItem.product ? Item : x
),
};
} else {
return {
...state,
cartItems: [...state.cartItems, Item],
};
}
default:
return state;
}
}
export default cartReducer;
I have tried multiple approaches but those did not help me