Commit 1ac8158f authored by 박상호's avatar 박상호 🎼
Browse files

productList subcategory making

parent 33124f62
...@@ -24,6 +24,7 @@ function App() { ...@@ -24,6 +24,7 @@ function App() {
<Route path="/login" component={Login} /> <Route path="/login" component={Login} />
<Route path="/signup" component={Signup} /> <Route path="/signup" component={Signup} />
<Route path="/product/:productId" component={Product} /> <Route path="/product/:productId" component={Product} />
<Route path="/categories/:main/:sub" component={ProductsList} />
<Route path="/categories/:main" component={ProductsList} /> <Route path="/categories/:main" component={ProductsList} />
<Route path="/admin" component={Admin} /> <Route path="/admin" component={Admin} />
<Route path="/regist" component={ProductRegist} /> <Route path="/regist" component={ProductRegist} />
......
...@@ -17,6 +17,7 @@ function SubNav() { ...@@ -17,6 +17,7 @@ function SubNav() {
const url = ele.toLowerCase() const url = ele.toLowerCase()
list.push( list.push(
<Nav.Link as={Link} to={`/categories/${url}`}>{ele}</Nav.Link> <Nav.Link as={Link} to={`/categories/${url}`}>{ele}</Nav.Link>
//categories/${SubNav.url}/&{url}
) )
}) })
setCategoriesDiv(list) setCategoriesDiv(list)
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import ListCard from '../Components/ListCard'; import ListCard from '../Components/ListCard';
import Pagination from '../Components/Pagination';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth'; import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup } from 'react-bootstrap';
import { Container, Row, Col, Form, FormControl, Button, Dropdown } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
function ProductsList({ match }) { function ProductsList({ match }) {
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase()) const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
const [subcategory, setSubcategory] = useState([]) const [subcategory, setSubcategory] = useState([])
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [sub, setSub] = useState([])
const [error, setError] = useState('') const [error, setError] = useState('')
// const user=isAuthenticated() useEffect(() => {
setMainCategory(match.params.main.toUpperCase())
}, [match.params.main])
useEffect(() => { useEffect(() => {
getSubsCategories() getSubsCategories([])
getProductlist() getProductlist()
}, [mainCategory]) }, [mainCategory])
useEffect(() => {
setMainCategory(match.params.main.toUpperCase())
}, [match.params.main])
function handleSearch() { function handleSearch() {
} }
// async function handleClick(subCategory) { async function getSubsCategories([]) {
// try {
// const response = await axios.get(`/api/product/getproduct/${subCategory}`)
// console.log("response.data=", response.data)
// setProductlist(response.data)
// } catch (error) {
// catchErrors(error, setError)
// }
// }
// function handleSubmit(e) {
// e.preventDefault()
// }
async function getSubsCategories() {
try { try {
const response = await axios.get(`/api/categories/sub/${mainCategory}`) const response = await axios.get(`/api/categories/sub/${mainCategory}`)
console.log("sub", response.data) setSubcategory(Object.values(response.data)[0])
setSubcategory(response.data)
console.log("response data=", response.data)
console.log("object value=", Object.values(response.data));
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
} }
...@@ -59,29 +45,16 @@ function ProductsList({ match }) { ...@@ -59,29 +45,16 @@ function ProductsList({ match }) {
const response = await axios.get(`/api/product/getproduct/${mainCategory}`) const response = await axios.get(`/api/product/getproduct/${mainCategory}`)
console.log("response.data=", response.data) console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
} }
function handleClick(e){
e.preventDefault()
return getsubproductlist()
}
async function getsubproductlist(){
try {
const response = await axios.get(`/api/product/getproduct/${subcategory}`)
console.log("response.data sub=",response.data)
setProductlist(response.data)
} catch (error) {
catchErrors(error,setError)
}
}
return ( return (
<div> <div>
{console.log("main=",mainCategory)}
<style type="text/css"> <style type="text/css">
{` {`
a, a:hover, a:active { a, a:hover, a:active {
...@@ -101,30 +74,34 @@ function ProductsList({ match }) { ...@@ -101,30 +74,34 @@ function ProductsList({ match }) {
`} `}
</style> </style>
<Container> <Container>
<Row className="justify-content-center" > <Row className="justify-content-center">
<Col sm={10} xs={12} > <Col sm={10} xs={12} >
<h1 style={{ fontSize: "3rem" }} className="text-center">{mainCategory}</h1> <h1 style={{ fontSize: "3rem" }} className="text-center">{mainCategory}</h1>
<div className="text-center">{subcategory.map((ele) => (
<Button className="m-1" onClick={(ele) => handleClick(ele)}>{ele}</Button>
))}</div> <div className="text-center">
<ButtonGroup className="d-flex flex-wrap" variant="outline-light secondary">
{subcategory.map(el => <Button className="m-1" variant="secondary">{el}</Button>)}
</ButtonGroup>
</div>
</Col> </Col>
</Row> </Row>
<Row className="justify-content-end mx-0 my-5"> <Row className="justify-content-end mx-0 my-5">
<Dropdown> <Dropdown>
<Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle> <Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle>
<Dropdown.Menu> <Dropdown.Menu>
<Dropdown.Item>인기상품</Dropdown.Item> <Dropdown.Item>인기상품</Dropdown.Item>
<Dropdown.Item>신상품</Dropdown.Item> <Dropdown.Item>신상품</Dropdown.Item>
<Dropdown.Item>낮은가격</Dropdown.Item> <Dropdown.Item>낮은가격</Dropdown.Item>
<Dropdown.Item>높은가격</Dropdown.Item> <Dropdown.Item>높은가격</Dropdown.Item>
</Dropdown.Menu> </Dropdown.Menu>
</Dropdown> </Dropdown>
<Form as={Row} onSubmit={handleSearch} className="justify-content-end mx-0"> <Form as={Row} onSubmit={handleSearch} className="justify-content-end mx-0">
<FormControl type="text" placeholder="Search" style={{ width: "13rem" }} /> <FormControl type="text" placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="search px-2"> <Button type="submit" className="search px-2">
<img src="/icon/search.svg" width="20" height="20" /> <img src="/icon/search.svg" width="20" height="20" />
</Button> </Button>
</Form> </Form>
</Row> </Row>
<Row md={8} sm={12} className="justify-content-start m-2"> <Row md={8} sm={12} className="justify-content-start m-2">
{productlist.map(pro => ( {productlist.map(pro => (
......
...@@ -3,6 +3,7 @@ import Category from "../schemas/Category.js"; ...@@ -3,6 +3,7 @@ import Category from "../schemas/Category.js";
const getCategory = async (req, res) => { const getCategory = async (req, res) => {
try { try {
const category = await Category.find({}, { _id: 0 }) const category = await Category.find({}, { _id: 0 })
console.log("main= ", category);
res.json(category) res.json(category)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -10,17 +11,64 @@ const getCategory = async (req, res) => { ...@@ -10,17 +11,64 @@ const getCategory = async (req, res) => {
} }
} }
const getSubCategory = (req, res) => { const getSubCategory = async (req, res) => {
console.log(req.params);
const { sub } = req.params
try {
const subcategory = await Category.findOne({}, { _id: 0}).select(`${sub}`)
console.log("sub= ",subcategory);
res.json(subcategory);
} catch (error) {
res.status(500).send('카테고리를 불러오지 못했습니다.')
}
}
const getToHome = async (res, req) => {
try {
const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=", bestProduct)
console.log("new=", newProduct)
res.json(bestProduct, newProduct)
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
}
} }
const getsubId = (req, res, next, sub) => {
// const subcategory = await category.find({"Dress"})
console.log('sub=', sub)
const getsubId = async (req, res, next, ele) => {
try {
const sub = await Category.find({ele})
if (!sub) {
res.status(404).send('카테고리가 존재하지 않습니다.')
} req.category = sub
req.subcategory = sub
next()
}
catch (error) {
console.log(error);
res.status(500).send('카테고리를 불러오지 못했습니다.')
}
next() next()
} }
// const userById = async (req, res, next, id) => {
// try {
// const user = await User.findById(id)
// if (!user) {
// res.status(404).send('사용자를 찾을 수 없습니다')
// }
// req.account = user
// next()
// } catch (error) {
// console.log(error);
// res.status(500).send('사용자 아이디 검색 실패')
// }
// }
export default { getCategory, getsubId, getSubCategory } export default { getCategory, getsubId, getSubCategory, getToHome }
\ No newline at end of file \ No newline at end of file
...@@ -9,6 +9,6 @@ router.route('/main') ...@@ -9,6 +9,6 @@ router.route('/main')
router.route('/sub/:sub') router.route('/sub/:sub')
.get(categoryCtrl.getSubCategory) .get(categoryCtrl.getSubCategory)
router.param('sub',categoryCtrl.getsubId) // router.param('sub',categoryCtrl.getsubId)
export default router export default router
\ No newline at end of file
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