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

product랑 shoppingCart 수정

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