I have products and a cart on the same page. So you can imagine they both belong to the same parent (HomeScreen). So what I am trying to do is in the product component, there is an add button, and whenever it is clicked I want to show this product in the cart and the quantity should be increased, whenever I click the button. Here is the product component:
import React, { useEffect, useState } from 'react';
export default function Product(props) {
const { product } = props;
const [qty, setQty] = useState(1);
const addToCartHandler = () => {
};
return (
<div key={product._id} className="col-lg-3 col-md-3 col-sm-4 col-xs-6 product">
<div className="card">
<div className="image-area">
</div>
</div>
<div className="products-body">
<div className="price">${product.price}</div>
<div className="product-name">{product.name}</div>
<button className="add-button" onClick={addToCartHandler}>Add</button>
</div>
</div>
);
}
And here is the Cart component:
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { addToCart } from "../../actions/cartActions";
export default function Cart(props) {
const productId = props.match.params.added;
const qty = 0;
const dispatch = useDispatch();
useEffect(() => {
if (productId) {
dispatch(addToCart(productId, qty));
}
}, [dispatch, productId, qty]);
return (
<div className="cart-box">
<p>
ADD TO CART : ProductID: {productId} Qty: {qty}
</p>
</div>
);
}
My cart action:
import Axios from 'axios';
import { CART_ADD_ITEM } from '../constants/cartConstants';
export const addToCart = (productId, qty) => async (dispatch, getState) => {
const { data } = await Axios.get(`/api/products/${productId}`);
dispatch({
type: CART_ADD_ITEM,
payload: {
name: data.name,
price: data.price,
product: data.added,
qty,
},
});
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
};
I don't know how to do it that's why addToCartHandler is empty. So it should be like in the image. Hope it is clear right now.
