ProductRegist.js 9.21 KB
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
import React, { useState, useEffect, useRef } from 'react';
2
import { Redirect } from 'react-router-dom';
kusang96's avatar
dd    
kusang96 committed
3
import { Row, Col, Button, Form, Container, Alert } from 'react-bootstrap';
kusang96's avatar
kusang96 committed
4
import axios from 'axios';
5
import catchErrors from '../utils/catchErrors';
이재연's avatar
0113    
이재연 committed
6
import { Redirect } from 'react-router-dom';
Jiwon Yoon's avatar
Jiwon Yoon committed
7

8
let color = {}
Jiwon Yoon's avatar
Jiwon Yoon committed
9
10
let preColors = []
let colorHtml = []
11
let list = []
Kim, Subin's avatar
Kim, Subin committed
12
13

function ProductsRegist() {
14
15
16
17
18
19
    const INIT_PRODUCT = {
        pro_name: '',
        price: 0,
        stock: 0,
        main_category: '',
        sub_category: [],
Jiwon Yoon's avatar
Jiwon Yoon committed
20
21
        sizes: [],
        colors: [],
22
23
24
25
        description: '',
        main_image: [],
        detail_image: []
    }
kusang96's avatar
kusang96 committed
26
    const [categorys, setCategorys] = useState({ 0: [], 1: [[]] })
27
28
29
    const [product, setProduct] = useState(INIT_PRODUCT)
    const [categoryNum, setCategoryNum] = useState(0)
    const [tag, setTag] = useState(0)
kusang96's avatar
dd    
kusang96 committed
30
    const [error, setError] = useState('')
31
32
33
    const [success, setSuccess] = useState(false)
    const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })

kusang96's avatar
kusang96 committed
34
35
36
37
38
39
40
41
42
    useEffect(async () => {
        try {
            const response = await axios.get('/api/categorys')
            const data = response.data[0]
            setCategorys([Object.keys(data), Object.values(data)])
        } catch (error) {
            catchErrors(error, setError)
        }
    }, [])
43
44
45
46
47
48
49
50
51
52

    function addCategory() {
        console.log(product)
        list.push(
            <div>
                <span i={tag}>{product["main_category"]} / {product["sub_category"][tag]}</span>
                <input type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteCategory} />
            </div>)
        setTag(tag + 1)
    }
kusang96's avatar
kusang96 committed
53

54
55
56
    function deleteCategory(e) {
        const categ = e.target.parentNode
        categ.remove()
kusang96's avatar
kusang96 committed
57
        product["sub_category"].splice(categ.firstElementChild.getAttribute("i"), 1)
58
    }
kusang96's avatar
kusang96 committed
59

60
61
62
    function handleCheckBox(e) {
        setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
63

64
    function addColor() {
Jiwon Yoon's avatar
Jiwon Yoon committed
65
66
67
        preColors.push(color["colors"])
        colorHtml.push(
            <p>{color["colors"]}</p>
68
        )
kusang96's avatar
kusang96 committed
69
        setProduct({ ...product, "colors": preColors })
Jiwon Yoon's avatar
Jiwon Yoon committed
70
    }
71

kusang96's avatar
kusang96 committed
72
73
    function colorChange(e) {
        color[e.target.name] = e.target.value
74
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
75
76

    function handleChange(event) {
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
77
        const { name, value, files } = event.target
kusang96's avatar
kusang96 committed
78
79
80
        console.log("event.target.name=", name, "event.target.value=", value)
        if (name === "sub_category") {
            product[name].push(value)
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
81
        } else if (files) {
kusang96's avatar
dd    
kusang96 committed
82
            setProduct({ ...product, [name]: files })
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
83

kusang96's avatar
dd    
kusang96 committed
84
85
86
        } else {
            setProduct({ ...product, [name]: value })
        }
87
88
89
        if (event.target.name === "main_category") {
            setCategoryNum(event.target.selectedIndex - 1)
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
90
91
    }

kusang96's avatar
dd    
kusang96 committed
92
    async function handleSubmit(e) {
Jiwon Yoon's avatar
Jiwon Yoon committed
93
        e.preventDefault()
94
95
96
97
98
99
        const sizes = []
        for (let [key, value] of Object.entries(checked)) {
            if (value === true) {
                sizes.push(key)
            }
        }
kusang96's avatar
kusang96 committed
100
        product["sizes"] = sizes
kusang96's avatar
kusang96 committed
101
        const formData = new FormData();
이재연's avatar
0113    
이재연 committed
102
103
104
105
        for (let key in product) {
            if (key === "main_imgUrl" ||key === "detail_imgUrl") {
                console.log(product[key][0])
                formData.append(key, product[key][0])
kusang96's avatar
dd    
kusang96 committed
106
107
108
109
110
            } else {
                formData.append(key, product[key])
            }
        }
        try {
이재연's avatar
0113    
이재연 committed
111
112
113
            const response = axios.post('/api/product/regist', formData)
            // setSuccess(true)
            console.log(response)
kusang96's avatar
dd    
kusang96 committed
114
115
        } catch (error) {
            catchErrors(error, setError)
kusang96's avatar
kusang96 committed
116
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
117
118
    }

119
120
    if (success) {
        return <Redirect to='/' />
121
    }
kusang96's avatar
kusang96 committed
122

Kim, Subin's avatar
Kim, Subin committed
123
    return (
kusang96's avatar
kusang96 committed
124
125
126
        <Container className="mt-5">
            <Row className="justify-content-md-center">
                <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
127
                    {error && <Alert variant="danger" className="text-center">{error}</Alert>}
kusang96's avatar
kusang96 committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
                    <h2 className="text-center mt-5 font-weight-bold">상품등록</h2>
                    <Form className="p-5" onSubmit={handleSubmit}>
                        <Form.Group controlId="productNameform">
                            <Form.Label>상품명</Form.Label>
                            <Form.Control type="text" name="pro_name" placeholder="상품명" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group controlId="productAmountform">
                            <Form.Label>재고</Form.Label>
                            <Form.Control type="text" name="stock" placeholder="숫자만 입력해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group controlId="productPriceform">
                            <Form.Label>가격</Form.Label>
                            <Form.Control type="text" name="price" placeholder="숫자만 입력해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>분류</Form.Label>
                            <Row>
                                <Col md={4}>
                                    <Form.Control as="select" name="main_category" onChange={handleChange}>
                                        <option value="" >상위분류</option>
                                        {categorys[0].map((main) => (
                                            <option value={main}>{main}</option>
                                        ))}
                                    </Form.Control>
                                </Col>
                                <Col md={6}>
                                    <Form.Control as="select" name="sub_category" onChange={handleChange}>
                                        <option value="" >하위분류</option>
                                        {categorys[1][categoryNum].map((sub) => (
                                            <option value={sub}>{sub}</option>
                                        ))}
                                    </Form.Control>
                                </Col>
                                <Col >
                                    <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
                                </Col>
                            </Row>
                            {list.map((element) => element)}
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>사이즈</Form.Label>
                            <Form.Check type="checkbox" name="sizes" label="Free" value="Free" onChange={handleCheckBox} />
                            <Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} />
                            <Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} />
                            <Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} />
                            <Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} />
                            <Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>색상</Form.Label>
                            <Row>
                                <Col md={10}>
                                    <Form.Control as="textarea" rows={1} name="colors" placeholder="색상" onChange={colorChange} />

                                </Col>
                                <Col>

                                    <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
                                </Col>
                            </Row>
                            {colorHtml.map((element) => element)}
                        </Form.Group>

                        <Form.Group controlId="productDescriptionform">
                            <Form.Label>상품설명</Form.Label>
                            <Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>대표이미지</Form.Label>
                            <Form.File id="productImageform" name="main_image" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>상세이미지</Form.Label>
                            <Form.File id="productImageform" name="detail_image" onChange={handleChange} />
                        </Form.Group>
                        <Button className="float-right" type="submit" style={{ background: '#91877F', borderColor: '#91877F' }}>등록</Button>
                    </Form>
                </Col>
            </Row>
        </Container>
Kim, Subin's avatar
Kim, Subin committed
208
209
210
211
    )
}

export default ProductsRegist