Commit 8258442f authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

product랑 shoppingCart 수정

parent 7bca069c
......@@ -15,10 +15,10 @@ function CartCard(props) {
</Col>
<Col md={6} className="p-2">
<Card.Body>
<input type="image" name={String(e.productId._id)} alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={props.deleteCart} />
<input type="image" name={String(e._id)} alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={props.deleteCart} />
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량</Card.Text>
<div>
<input type="image" alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} />
......
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Card, Button } from 'react-bootstrap';
import { Redirect } from 'react-router-dom';
import catchErrors from '../utils/catchErrors';
const preCart = []
function Product({ match, location }) {
const [product, setProduct] = useState(location.state)
const [cart, setCart] = useState(location.state)
const [color, setColor] = useState("")
const [size, setSize] = useState("")
const [cart, setCart] = useState([])
const [error, setError] = useState('')
const [selected, setSelected] = useState({ sizes: false, colors: false })
const [count, setCount] = useState(1)
const [price, setPrice] = useState(0)
useEffect(() => {
if (selected.sizes === true && selected.colors === true) {
if (size && color) {
pushOptions()
console.log(preCart)
console.log(cart)
}
}, [cart])
}, [size, color])
function handleClick(e) {
......@@ -26,79 +29,74 @@ function Product({ match, location }) {
}
function pushOptions() {
preCart.push(cart)
setCart([...cart, { color, size, productId: product.id }])
selected.sizes = false
selected.colors = false
setPrice(product.price+price)
setColor("")
setSize("")
setPrice(product.price + price)
}
function handleChange(e) {
const { name, value } = e.target
if (e.target.name === "sizes") {
setCart({ ...cart, [name]: value })
if (name === "sizes") {
// setPreCart({ ...preCart, [name]: value })
setSize(value)
selected.sizes = true
} else if (e.target.name === "colors") {
setCart({ ...cart, [name]: value })
} else if (name === "colors") {
// setPreCart({ ...preCart, [name]: value })
setColor(value)
selected.colors = true
}
// setCart({ ...cart, [name]: value })
// handleCreate()
}
function listDelete(e) {
function deleteOption(e) {
e.preventDefault()
const parent = e.target.parentNode
parent.remove()
const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
setCart(asd)
}
function handleCreate() {
// if (product !== undefined) {
// if (product.colors !== "" && product.sizes !== "") {
// cart.push(
// <div className="d-flex justify-content-between my-2" >
// <p>{product.color} {product.size} </p>
// <input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} />
// <p style="margin-bottom: 0px">{product.price}</p>
// </div>
// )
// const list = document.getElementById('list')
// list.style.borderBottom = "1px solid"
// const shopping = document.createElement('div')
// shopping.className = "d-flex justify-content-between my-2"
// shopping.innerHTML = `${product.color} / ${product.size}
// <input type="number" min="0" max="10" value="1" style="width: 40px" />
// <p style="margin-bottom: 0px">14,000원</p>`
// const deleteA = document.createElement('a')
// deleteA.innerText = 'X'
// deleteA.addEventListener('click', listDelete)
// shopping.appendChild(deleteA)
// list.appendChild(shopping)
// }
// }
function handleCount(e) {
e.preventDefault()
// const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
const asd= cart.map((el)=>{
if(el.color !== e.target.id || el.size !== e.target.name){
return {el}
} else {
return {...el, count : e.target.value}
}
})
// const index = product["sub_category"].findIndex((item)=>{return item === e.target.name})
// product["sub_category"].splice(index, 1)
setCart(asd)
setCount(e.value)
}
async function addCart() {
console.log(cart)
if (localStorage.getItem('id')) {
// preCart(color, size, count), productId(productlist에서 props), userId(로컬) 를 보내줌
try {
setError('')
const response = await axios.put('/api/cart/addcart', {
userId: localStorage.getItem('loginStatus'),
productId: "a8f4d63ead77717f940a2b27deb707a6",
products: preCart
userId: localStorage.getItem('id'),
// productId: product.id,
products: cart
})
console.log(response)
} catch (error) {
catchErrors(error, setError)
}
} else {
alert("로그인을 해주세요.")
return <Redirect to='/login' />
}
}
// useEffect(() => {
// handleCreate()
// }, [product])
return (
<div>
{console.log("match=",match.params, "location=",location.state, "product=",product)}
{/* {console.log("match=", match.params, "location=", location.state, "product=", product)} */}
<style type="text/css">
{`
.btn {
......@@ -122,29 +120,37 @@ function Product({ match, location }) {
<Form style={{ borderBottom: "1px solid" }}>
<Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}>
<Form.Label>색상</Form.Label>
<Form.Control as="select" className="mb-2" name="colors" defaultValue="옵션 선택" onChange={handleChange}>
<Form.Control as="select" className="mb-2" name="colors" value={color} defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option>
{product.colors.map((e) => (
<option>{e}</option>
))}
</Form.Control>
<Form.Label>사이즈</Form.Label>
<Form.Control as="select" className="mb-2" name="sizes" defaultValue="옵션 선택" onChange={handleChange}>
<Form.Control as="select" className="mb-2" name="sizes" value={size} defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option>
{product.sizes.map((e) => (
<option>{e}</option>
))}
</Form.Control>
</Form.Group>
{preCart.map((e) => (
<div>{e.colors}/{e.sizes}</div>
{cart.map((e) => (
<div>
<span>{e.color}/{e.size}</span>
<input onClick={deleteOption} id={e.color} name={e.size} type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" />
<span>{e.price}</span>
<span className="float-right mx-2">
<input type='number' id={e.color} name={e.size} onChange={handleCount} value={count} style={{ width: '3rem' }} className="text-center" />
</span>
</div>
))}
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Col> 금액</Col>
<Col className="text-right">{price}</Col>
</Row>
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Button onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
<Button type='button' onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
<Button style={{ width: "49%" }}>구매하기</Button>
</Row>
</Form>
......
......@@ -120,15 +120,22 @@ function ProductsRegist() {
}
}
product["sizes"] = sizes
console.log(product)
const formData = new FormData();
for (let key in product) {
if (key === "main_image" ||key === "detail_image") {
console.log(product[key][0])
// console.log(product[key][0])
formData.append(key, product[key][0])
} else {
} else if(key === "sizes" || key === "colors"){
for (let i = 0; i < product[key].length ; i++){
formData.append([key], product[key][i])
}
}
else {
formData.append(key, product[key])
}
}
// console.log(formData)
try {
const response = await axios.post('/api/product/regist', formData)
console.log(response)
......@@ -199,7 +206,7 @@ function ProductsRegist() {
<Form.Label>색상</Form.Label>
<Row>
<Col md={10}>
<Form.Control as="textarea" rows={1} name="colors" value={color["colors"]} placeholder="색상" onChange={handleColor} />
<Form.Control as="textarea" rows={1} name="colors" placeholder="색상" onChange={handleColor} />
</Col>
<Col>
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
......
......@@ -33,8 +33,11 @@ function ShoppingCart() {
//장바구니 DB에서 해당 항목 삭제
console.log(e.target.name)
try {
const response = await axios.post('/api/cart/deletecart', { cartId: e.target.name })
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)
}
......
......@@ -6,7 +6,7 @@ const addcart = async (req, res) => {
const cart = await Cart.findOne({ userId: userId })
await Cart.updateOne(
{ _id: cart._id },
{$set: {products: products}}
{$push: {products: products}}
)
res.status(200).send('카트에 저장되었습니다.')
} catch (error) {
......@@ -30,10 +30,18 @@ const showcart = async (req, res) => {
const deletecart = async (req, res) => {
console.log(req.body)
const { cartId } = req.body
const { userId,cartId } = req.body
try {
await Cart.deleteOne({ _id: cartId })
res.send("삭제완료")
const cart = await Cart.findOneAndUpdate(
{ userId: userId },
{ $pull: { products: {_id:cartId} } },
{ new: true }
).populate({
path: 'products.productId',
model: 'Product'
})
// res.send("삭제완료")
res.json(cart)
} catch (error) {
console.log(error)
res.status(500).send('해당 카트를 삭제하지 못했습니다.')
......
......@@ -17,10 +17,10 @@ const CartSchema = new mongoose.Schema({
type: ObjectId,
ref: 'Product'
},
sizes: {
size: {
type: String
},
colors: {
color: {
type: String
}
}
......
import mongoose from 'mongoose'
const { String, Number } = mongoose.Schema.Types
const { String, Array, Number } = mongoose.Schema.Types
const ProductSchema = new mongoose.Schema({
pro_name: {
......@@ -33,7 +33,7 @@ const ProductSchema = new mongoose.Schema({
required: true,
},
sub_category: {
type: [String],
type: Array,
required: true,
},
description: {
......@@ -45,7 +45,7 @@ const ProductSchema = new mongoose.Schema({
required: true
},
detail_imgUrls: {
type: [String]
type: Array
}
}, {
timestamps: true
......
Markdown is supported
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