import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import ListCard from '../Components/ListCard'; import axios from 'axios'; import catchErrors from '../utils/catchErrors'; import { isAuthenticated } from '../utils/auth'; import { Button, Container } from 'react-bootstrap'; function ShoppingCart() { const [error, setError] = useState('') const [cart, setCart] = useState([]) const [finalCart, setFinalCart] = useState([]) const [finalPrice, setFinalPrice] = useState(0) const user = isAuthenticated() useEffect(() => { getCart() }, [user]) useEffect(() => { price() }, [cart]) 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 price() { let price = 0 const list = cart.filter((el) => el.checked === true) list.map((el) => { price = el.count * el.productId.price + price }) setFinalPrice(price) setFinalCart(list) } function checkedCart(e) { const cartCheck = cart.map((el) => { if (el._id === e.target.name) { return { ...el, checked: !el.checked } } else { return { ...el } } }) setCart(cartCheck) } async function deleteCart(e) { try { setError('') const response = await axios.post('/api/cart/deletecart', { userId: user, cartId: e.target.name }) setCart(response.data.products) } catch (error) { catchErrors(error, setError) } } async function getCart() { try { setError('') const response = await axios.get(`/api/cart/showcart/${user}`) const addChecked = response.data.map((el) => { return { ...el, checked: true } }) setCart(addChecked) } catch (error) { catchErrors(error, setError) } } function putCheckedCart() { try { setError('') const response = axios.post(`/api/cart/changecart`, { userId: user, products: cart }) } catch (error) { catchErrors(error, setError) } } return (

장바구니

주문상품정보

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