Commit 46dec4ea authored by Rasoul Madani's avatar Rasoul Madani
Browse files

فیلم22

parent 1cbaf144
import Axios from "axios";
import {CART_ADD_ITEM} from '../constants/cartConstants'
import {CART_ADD_ITEM,CART_REMOVE_ITEM} from '../constants/cartConstants'
export const addToCart = (productId, qty) => async (dispatch) => {
const { data } = await Axios.get(`/api/products/${productId}`);
dispatch({
......@@ -14,3 +14,10 @@ export const addToCart = (productId, qty) => async (dispatch) => {
}
})
};
export const removeFromCart = (id)=>(dispatch)=>{
dispatch({
type: CART_REMOVE_ITEM,
payload: id
})
}
export const CART_ADD_ITEM = "CART_ADD_ITEM";
export const CART_REMOVE_ITEM = "CART_REMOVE_ITEM";
import { CART_ADD_ITEM } from "../constants/cartConstants";
import { CART_ADD_ITEM, CART_REMOVE_ITEM } from "../constants/cartConstants";
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
......@@ -17,7 +17,10 @@ export const cartReducer = (state = { cartItems: [] }, action) => {
cartItems: [...state.cartItems, action.payload],
};
}
case CART_REMOVE_ITEM:
return {
cartItems: state.cartItems.filter((x) => x.product !== action.payload),
};
default:
return state;
}
......
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../actions/cartActions";
import { addToCart, removeFromCart } from "../actions/cartActions";
import { Link } from "react-router-dom";
import MessageBox from "../components/MessageBox";
......@@ -12,6 +12,9 @@ export default function CartScreen(props) {
const qty = props.location.search
? Number(props.location.search.split("=")[1])
: 1;
const removeFromCartHandler = (id) => {
dispatch(removeFromCart(id));
};
useEffect(() => {
dispatch(addToCart(productId, qty));
}, [dispatch, productId, qty]);
......@@ -51,6 +54,14 @@ export default function CartScreen(props) {
</select>
</div>
<div>$ {item.price}</div>
<div>
<button
type="button"
onClick={() => removeFromCartHandler(item.product)}
>
Delete
</button>
</div>
</div>
</li>
))}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment