import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstrap';
import axios from 'axios';
import catchErrors from '../utils/catchErrors';
let preColors = []
let colorHtml = []
let list = []
function ProductsRegist() {
const INIT_PRODUCT = {
pro_name: '',
price: 0,
stock: 0,
main_category: '',
sub_category: [],
sizes: [],
colors: [],
description: '',
main_image: [],
detail_image: []
}
const [categories, setCategories] = useState({ 0: [], 1: [[]] })
const [product, setProduct] = useState(INIT_PRODUCT)
const [categoryNum, setCategoryNum] = useState('')
const [tag, setTag] = useState(0)
const [subCate, setSubCate] = useState('')
const [color, setColor] = useState({})
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
const [disabled, setDisabled] = useState(true)
const [loading, setLoading] = useState(false)
const selectRef = useRef(null)
const colorRef = useRef(null)
useEffect(async () => {
try {
const response = await axios.get('/api/categories/main')
const data = response.data[0]
setCategories([Object.keys(data), Object.values(data)])
} catch (error) {
catchErrors(error, setError)
}
}, [])
useEffect(() => {
const isProduct = Object.values(product).every(el => { console.log("el=", el); Boolean(el) })
isProduct ? setDisabled(false) : setDisabled(true)
}, [product])
function addCategory(e) {
if (selectRef.current.value === '') {
alert('하위 분류를 반드시 선택해 주세요.')
} else {
list.push(
{product["main_category"]} / {subCate}
)
setTag(tag + 1)
selectRef.current.selectedIndex = 0
}
}
function deleteCategory(e) {
e.target.parentNode.remove()
const index = product["sub_category"].findIndex((item) => { return item === e.target.name })
product["sub_category"].splice(index, 1)
setSubCate('')
console.log(product["sub_category"].length)
}
function handleCategory(e) {
const { name, value, selectedIndex } = e.target
if (name === "main_category") {
setCategoryNum(selectedIndex - 1)
}
if (name === "sub_category") {
product[name].push(value)
setSubCate(value)
} else {
setProduct({ ...product, [name]: value })
}
}
function handleCheckBox(e) {
setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
}
function addColor() {
preColors.push(color["colors"])
colorHtml.push(
{color["colors"]}
)
colorRef.current.value = ''
setProduct({ ...product, "colors": preColors })
}
function deleteColor(e) {
// console.log("e.name=",e.target.name)
e.target.parentNode.remove()
product["colors"].splice(e.name, 1)
// setColor({})
// console.log(product)
}
function handleColor(e) {
color[e.target.name] = e.target.value
}
function handleChange(event) {
const { name, value, files } = event.target
if (files) {
setProduct({ ...product, [name]: files })
} else {
setProduct({ ...product, [name]: value })
}
}
async function handleSubmit(e) {
e.preventDefault()
const sizes = []
for (let [key, value] of Object.entries(checked)) {
if (value === true) {
sizes.push(key)
}
}
product["sizes"] = sizes
console.log(product)
const formData = new FormData();
for (let key in product) {
if (key === "main_image" || key === "detail_image") {
formData.append(key, product[key][0])
} else if (key === "sizes" || key === "colors" || key === "sub_category") {
for (let i = 0; i < product[key].length; i++) {
formData.append([key], product[key][i])
}
}
else {
formData.append(key, product[key])
}
}
try {
setLoading(true)
setError('')
const response = await axios.post('/api/product/regist', formData)
console.log(response)
setSuccess(true)
} catch (error) {
catchErrors(error, setError)
} finally {
setLoading(false)
}
}
if (success) {
alert('상품 등록을 완료하였습니다.')
return
}
return (
{error && {error}}
상품등록
상품명
재고
가격
분류
0}>
{categories[0].map((main) => (
))}
{(categoryNum === '') ? '' : (categories[1][categoryNum].map((sub) => (
)))}
{list.map((element) => element)}
사이즈
색상
{colorHtml.map((element) => element)}
상품설명
대표이미지
상세이미지
)
}
export default ProductsRegist