import React, { useState, useEffect, useRef } from 'react'; import { Link, Redirect } from 'react-router-dom'; import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import axios from 'axios'; import catchErrors from '../utils/catchErrors'; import { isAuthenticated } from '../utils/auth' import CartCard from '../Components/CartCard'; function ShoppingCart() { const [error, setError] = useState('') const [cart, setCart] = useState([]) const [finalCart, setFinalCart] = useState([]) const [finalPrice, setFinalPrice] = useState(0) const user = isAuthenticated() useEffect(() => { getCart() console.log(cart) }, [user]) function plusNum(e) { const addCount = cart.map((el) => { if (el._id === e.target.name) { return { ...el, count: el.count+1} } else { return { ...el } } }) setCart(addCount) } function minusNum(e) { const addCount = cart.map((el) => { if (el._id === e.target.name) { return { ...el, count: el.count-1 } } else { return { ...el } } }) setCart(addCount) } function checkedCart(e) { let price = 0 const cartCheck = cart.map((el) => { if (el._id === e.target.name) { return { ...el, checked: !el.checked } } else { return { ...el } } }) const asd = cartCheck.filter((el) => el.checked === true) asd.map((el)=>{ price = el.count*el.productId.price + price }) setFinalPrice(price) setCart(cartCheck) setFinalCart(asd) } async function deleteCart(e) { //장바구니 DB에서 해당 항목 삭제 console.log(e.target.name) try { const response = await axios.post('/api/cart/deletecart', { userId: user, cartId: e.target.name }) console.log(response.data) setCart(response.data.products) } catch (error) { catchErrors(error, setError) } console.log('카트에 담긴 항목을 삭제했습니다.') } async function getCart() { try { setError('') const response = await axios.get(`/api/cart/showcart/${user}`) const addChecked = response.data.map((el) => { return { ...el, checked: false } }) console.log("addchecked=",addChecked) setCart(addChecked) } catch (error) { catchErrors(error, setError) } } function putCheckedCart(){ try { setError('') const response = axios.post(`/api/cart/changecart`, { userId:user, products: cart }) console.log(response.data) } catch (error) { catchErrors(error, setError) } } return (
{console.log(cart)}

장바구니

주문상품정보

{cart.length > 0 ? :
장바구니에 담긴 상품이 없습니다.
}
  • 총 상품금액 {finalPrice}원
  • 배송비 2500원
결제금액{finalPrice + 2500}원
) } export default ShoppingCart