Commit 34c5f591 authored by kusang96's avatar kusang96
Browse files

Pagination & delete 기능

parent fbce3d1a
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { Redirect, Route } from 'react-router-dom'; import { Redirect, Route } from 'react-router-dom';
import { isAdmin } from '../utils/auth'; import { isAdmin } from '../utils/auth';
function PrivateRoute({path, children}) { function PrivateRoute({ path, children }) {
if (isAdmin()) { if (isAdmin()) {
return ( return (
<Route path={path}> <Route path={path}>
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import axios from 'axios';
import catchError from '../utils/catchErrors';
import { Card, Button } from 'react-bootstrap'; import { Card, Button } from 'react-bootstrap';
function AllCard({ id, name, price, main_img }) { function AllCard({ id, name, price, main_img }) {
function handleDelete(e) { const [success, setSuccess] = useState(false)
const card = e.target.parentNode.parentNode const [error, setError] = useState('')
alert('해당 상품을 성공적으로 삭제하였습니다.') const cardRef = useRef(null)
card.remove()
async function handleDelete() {
const pro_id = cardRef.current.id
try {
setError('')
const response = await axios.delete(`/api/product/delete?pro_id=${pro_id}`)
alert('해당 상품을 성공적으로 삭제하였습니다.')
setSuccess(true)
} catch (error) {
catchError(error, setError)
setSuccess(false)
}
}
if (success) {
return <Redirect to="/admin" />
} }
return ( return (
<Card id={id} className="m-3" style={{ width: "18rem" }}> <Card id={id} ref={cardRef} className="m-3" style={{ width: "18rem" }}>
<Card.Img variant="top" src={main_img && `/images/${main_img}`} style={{ objectFit: "contain", height: "22rem" }} /> <Card.Img variant="top" src={main_img && `/images/${main_img}`} style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body> <Card.Body>
<Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title> <Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title>
......
...@@ -2,38 +2,36 @@ import React from 'react' ...@@ -2,38 +2,36 @@ import React from 'react'
import { Card, Row, Col } from 'react-bootstrap'; import { Card, Row, Col } from 'react-bootstrap';
function CartCard(props) { function CartCard(props) {
console.log(props)
return ( return (
<> <>
{props.cart.map((e) => ( {props.cart.map((e) => (
<Card> <Card>
<Row className="mx-1"> <Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto"> <Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" name={String(e._id)} onChange={props.checkedCart} /> <input className="" type="checkbox" name={String(e._id)} onChange={props.checkedCart} />
</Col> </Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col> </Col>
<Col md={6} className="p-2"> <Col md={6} className="p-2">
<Card.Body> <Card.Body>
<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} /> <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 className="mb-0">가격: {e.productId.price}</Card.Text> <Card.Text className="mb-0">가격: {e.productId.price}</Card.Text>
<Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text> <Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text>
<Card.Text >수량</Card.Text> <Card.Text >수량</Card.Text>
<div> <div>
<input type="image" name={String(e._id)} alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} /> <input type="image" name={String(e._id)} alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} />
<input type="number" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input> <input type="number" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input>
<input type="image" name={String(e._id)} alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} /> <input type="image" name={String(e._id)} alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} />
</div> </div>
</Card.Body> </Card.Body>
</Col> </Col>
</Row> </Row>
</Card> </Card>
)) ))
} }
</> </>
) )
} }
......
import React, { useState, useEffect, useRef } from 'react'; import React from 'react';
import { Card, Button } from 'react-bootstrap'; import { Card } from 'react-bootstrap';
function ListCard({ id, name, price, main_img }) { function ListCard({ id, name, price, main_img }) {
function handleDelete(e) {
const card = e.target.parentNode.parentNode
alert('해당 상품을 성공적으로 삭제하였습니다.')
card.remove()
}
return ( return (
<Card id={id} className="m-3" style={{ width: "18rem" }}> <Card id={id} className="m-3" style={{ width: "18rem" }}>
......
...@@ -21,7 +21,7 @@ function MainNav() { ...@@ -21,7 +21,7 @@ function MainNav() {
<img alt="카트" src="/icon/cart.svg" width="30" height="30" /> <img alt="카트" src="/icon/cart.svg" width="30" height="30" />
</Nav.Link> </Nav.Link>
</> </>
: ( : (
<> <>
<Nav.Link className="text-light" href='/login'>Login</Nav.Link> <Nav.Link className="text-light" href='/login'>Login</Nav.Link>
<Nav.Link className="text-light" href='/signup'>Sign Up</Nav.Link> <Nav.Link className="text-light" href='/signup'>Sign Up</Nav.Link>
......
import { Pagination } from "react-bootstrap"; import { Pagination } from "react-bootstrap";
import React from 'react'; import React from 'react';
function Paginations({ index, endPage, handlePage }) { function Paginations({ index, totalPages, handlePage }) {
return ( return (
<Pagination> <Pagination className="d-flex justify-content-center">
<style type="text/css">
{`
.page-link, .page-link:hover {
color: #91877F;
margin: 0;
border: 0;
}
.page-link:focus {
box-shadow: 0 0 0 0;
}
.page-item.active .page-link {
background-color: #CDC5C2;
border-color: #CDC5C2;
color: #fff;
}
`}
</style>
<Pagination.First onClick={() => handlePage(1)} /> <Pagination.First onClick={() => handlePage(1)} />
{index === 1 ? <Pagination.Prev onClick={()=>handlePage(index)} /> : <Pagination.Prev onClick={()=>handlePage(index - 1)} />} {index === 1 ? <Pagination.Prev onClick={()=>handlePage(index)} /> : <Pagination.Prev onClick={()=>handlePage(index - 1)} />}
{index === endPage-1 ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""} {index === totalPages && index > 4 ? <Pagination.Item onClick={()=>handlePage(index - 4)}>{index - 4}</Pagination.Item> : ""}
{index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 4)}>{index - 4}</Pagination.Item> : ""} {index > 3 && index >= totalPages-1 ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{index < 3 ? "" : <Pagination.Item onClick={()=>handlePage(index - 2)}>{index - 2}</Pagination.Item>} {index < 3 ? "" : <Pagination.Item onClick={()=>handlePage(index - 2)}>{index - 2}</Pagination.Item>}
{index === 1 ? "" : <Pagination.Item onClick={()=>handlePage(index - 1)}>{index - 1}</Pagination.Item>} {index === 1 ? "" : <Pagination.Item onClick={()=>handlePage(index - 1)}>{index - 1}</Pagination.Item>}
<Pagination.Item active>{index}</Pagination.Item> <Pagination.Item active>{index}</Pagination.Item>
{index === endPage ? "" : <Pagination.Item onClick={()=>handlePage(index + 1)}>{index + 1}</Pagination.Item>} {index === totalPages ? "" : <Pagination.Item onClick={()=>handlePage(index + 1)}>{index + 1}</Pagination.Item>}
{index > endPage-2 ? "" : <Pagination.Item onClick={()=>handlePage(index + 2)}>{index + 2}</Pagination.Item>} {index > totalPages-2 ? "" : <Pagination.Item onClick={()=>handlePage(index + 2)}>{index + 2}</Pagination.Item>}
{index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""} {index < totalPages-3 && index >= 1 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""}
{index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 4)}>{index + 4}</Pagination.Item> : ""} {index < totalPages-4 && index >= 1 ? <Pagination.Item onClick={()=>handlePage(index + 4)}>{index + 4}</Pagination.Item> : ""}
{index === 2 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""} {index === totalPages ? <Pagination.Next onClick={()=>handlePage(index)} /> : <Pagination.Next onClick={()=>handlePage(index + 1)} />}
{index === endPage ? "" : <Pagination.Next onClick={()=>handlePage(index + 1)} />}
<Pagination.Last onClick={() =>handlePage(endPage)} /> <Pagination.Last onClick={() =>handlePage(totalPages)} />
</Pagination> </Pagination>
) )
} }
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { Redirect, Route } from 'react-router-dom'; import { Redirect, Route } from 'react-router-dom';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
function PrivateRoute({path, children}) { function PrivateRoute({ path, children }) {
if (isAuthenticated()) { if (isAuthenticated()) {
return ( return (
<Route path={path}> <Route path={path}>
......
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react';
import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form, Modal, Alert } from 'react-bootstrap' import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form, Modal, Alert } from 'react-bootstrap';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
...@@ -17,7 +17,7 @@ function Account() { ...@@ -17,7 +17,7 @@ function Account() {
const [error, setError] = useState("") const [error, setError] = useState("")
const userId = isAuthenticated() const userId = isAuthenticated()
const [ordered, setOrdered] = useState('') const [ordered, setOrdered] = useState('')
async function getUsername(user) { async function getUsername(user) {
try { try {
...@@ -38,18 +38,16 @@ function Account() { ...@@ -38,18 +38,16 @@ function Account() {
if (files) { if (files) {
setAccount({ ...account, [name]: files }) setAccount({ ...account, [name]: files })
} else { } else {
console.log("name=", name, "value=", value);
setAccount({ ...account, [name]: value }) setAccount({ ...account, [name]: value })
} }
} }
const handleBasic = async (event) => { const handleBasic = async () => {
const formData = new FormData() const formData = new FormData()
formData.append('avatar', '') formData.append('avatar', '')
try { try {
if (userId) { if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData) const response = await axios.put(`/api/users/account/${userId}`, formData)
console.log(response.data)
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
...@@ -67,7 +65,6 @@ function Account() { ...@@ -67,7 +65,6 @@ function Account() {
try { try {
if (userId) { if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData) const response = await axios.put(`/api/users/account/${userId}`, formData)
console.log(response.data)
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
...@@ -78,8 +75,7 @@ function Account() { ...@@ -78,8 +75,7 @@ function Account() {
} }
} }
async function getOrdered({}) { async function getOrdered({ }) {
console.log("object")
try { try {
const response = await axios.get(`/api/users/addorder`) const response = await axios.get(`/api/users/addorder`)
setOrdered(response.data) setOrdered(response.data)
...@@ -88,7 +84,7 @@ function Account() { ...@@ -88,7 +84,7 @@ function Account() {
} }
} }
return ( return (
<Container className="px-3"> <Container className="px-3">
<style type="text/css"> <style type="text/css">
...@@ -178,7 +174,6 @@ function Account() { ...@@ -178,7 +174,6 @@ function Account() {
<a href="mailto:shoppingmall_KU@korea.ac.kr"> <a href="mailto:shoppingmall_KU@korea.ac.kr">
<small title="메일보내기"> * 문의 : shoppingmall_KU@korea.ac.kr </small> <small title="메일보내기"> * 문의 : shoppingmall_KU@korea.ac.kr </small>
</a> </a>
{/* 쇼핑몰 문의 메일보내기 */}
</Row> </Row>
</Col> </Col>
</Row> </Row>
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import AllCard from '../Components/AllCard'; import AllCard from '../Components/AllCard';
import Pagination from "../Components/Pagination"; import Pagination from "../Components/Pagination";
import axios from 'axios'; import axios from 'axios';
...@@ -11,38 +10,31 @@ function Admin() { ...@@ -11,38 +10,31 @@ function Admin() {
const [search, setSearch] = useState({ word: '' }) const [search, setSearch] = useState({ word: '' })
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [status, setStatus] = useState(INIT_STATUS) const [status, setStatus] = useState(INIT_STATUS)
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1)
const [per, setPer] = useState(10);
const [error, setError] = useState('') const [error, setError] = useState('')
const searchref = useRef(null) const searchref = useRef(null)
const indexOfLast = currentPage * per; const per = 10;
const indexOfFirst = indexOfLast - per;
useEffect(() => { useEffect(() => {
getProductlist() getProductlist()
}, []) }, [])
function paginate(items, index, itemNumber) { useEffect(() => {
const posts = []; setStatus({ indexOfFirst: (currentPage - 1) * per, indexOfLast: currentPage * per })
const startIndex = (index - 1) * itemNumber }, [currentPage])
for (var i = 0; i < itemNumber; i++) {
posts.push(items[(startIndex + i)])
}
return posts
}
function currentPosts(tmp) { function currentPosts(items) {
let currentPosts = 0; let currentPosts = 0;
currentPosts = tmp.slice(indexOfFirst, indexOfLast); currentPosts = items.slice(status.indexOfFirst, status.indexOfLast);
console.log("postsPerPage=",currentPage) return currentPosts
return currentPosts;
} }
async function getProductlist() { async function getProductlist() {
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct/all`) const response = await axios.get(`/api/product/getproduct/all`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -57,8 +49,8 @@ function Admin() { ...@@ -57,8 +49,8 @@ function Admin() {
try { try {
setError('') setError('')
const response = await axios.get(`/api/product/getproduct/all?product=${search.word}`) const response = await axios.get(`/api/product/getproduct/all?product=${search.word}`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} finally { } finally {
...@@ -80,8 +72,16 @@ function Admin() { ...@@ -80,8 +72,16 @@ function Admin() {
background-color: #CDC5C2; background-color: #CDC5C2;
border-color: #CDC5C2; border-color: #CDC5C2;
} }
.btn:hover {
.btn:hover, .btn:active, .btn:focus { background-color: #91877F;
border-color: #91877F;
}
.btn-primary.focus, .btn-primary:focus {
background-color: #91877F;
border-color: #91877F;
box-shadow: 0 0 0 0;
}
.btn-primary:not(:disabled):not(.disabled).active, .btn-primary:not(:disabled):not(.disabled):active, .show>.btn-primary.dropdown-toggle {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
} }
...@@ -99,7 +99,7 @@ function Admin() { ...@@ -99,7 +99,7 @@ function Admin() {
<AllCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} /> <AllCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
))} ))}
</Row> </Row>
<Pagination index={currentPage} totalPosts={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} />
</Container> </Container>
) )
} }
......
...@@ -12,7 +12,6 @@ const INIT_USER = { ...@@ -12,7 +12,6 @@ const INIT_USER = {
} }
function Login() { function Login() {
const [validated, setValidated] = useState(false); const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('') const [error, setError] = useState('')
...@@ -33,7 +32,7 @@ function Login() { ...@@ -33,7 +32,7 @@ function Login() {
setValidated(true); setValidated(true);
try { try {
setError('') setError('')
const response=await axios.post('/api/auth/login', user) const response = await axios.post('/api/auth/login', user)
handleLogin(response.data) handleLogin(response.data)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
...@@ -43,7 +42,7 @@ function Login() { ...@@ -43,7 +42,7 @@ function Login() {
if (success) { if (success) {
alert('로그인 되었습니다.') alert('로그인 되었습니다.')
window.location.href='/' window.location.href = '/'
} }
return ( return (
...@@ -72,7 +71,6 @@ function Login() { ...@@ -72,7 +71,6 @@ function Login() {
<Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicPassword"> <Form.Group controlId="formBasicPassword">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col> <Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
......
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode";
import { Container, Row, Col, Button, Form } from 'react-bootstrap';
import { Redirect, Link, useHistory } from 'react-router-dom'; import { Redirect, Link, useHistory } from 'react-router-dom';
import DaumPostcode from "react-daum-postcode";
import PaymentCard from '../Components/PaymentCard'; import PaymentCard from '../Components/PaymentCard';
import axios from 'axios';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { Container, Row, Col, Button, Form } from 'react-bootstrap';
function Payment({ match, location }) { function Payment({ match, location }) {
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
...@@ -46,7 +46,6 @@ function Payment({ match, location }) { ...@@ -46,7 +46,6 @@ function Payment({ match, location }) {
try { try {
setError('') setError('')
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
const preCart = response.data.filter((el) => el.checked === true) const preCart = response.data.filter((el) => el.checked === true)
if (preCart.length) { if (preCart.length) {
setCart(preCart) setCart(preCart)
...@@ -67,7 +66,6 @@ function Payment({ match, location }) { ...@@ -67,7 +66,6 @@ function Payment({ match, location }) {
userId: user, userId: user,
cartId: e.target.name cartId: e.target.name
}) })
console.log(response.data)
const preCart = response.data.products.filter((el) => el.checked === true) const preCart = response.data.products.filter((el) => el.checked === true)
setCart(preCart) setCart(preCart)
setOrder({ products: preCart }) setOrder({ products: preCart })
...@@ -78,7 +76,6 @@ function Payment({ match, location }) { ...@@ -78,7 +76,6 @@ function Payment({ match, location }) {
function handleReceiverInfo(e) { function handleReceiverInfo(e) {
const { name, value } = e.target const { name, value } = e.target
console.log(name, value)
setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } }) setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
} }
...@@ -98,11 +95,9 @@ function Payment({ match, location }) { ...@@ -98,11 +95,9 @@ function Payment({ match, location }) {
const handleComplete = (data) => { const handleComplete = (data) => {
let fullAddress = data.address; let fullAddress = data.address;
let extraAddress = ""; let extraAddress = "";
console.log(data)
if (data.addressType === "R") { if (data.addressType === "R") {
if (data.bname !== "") { if (data.bname !== "") {
extraAddress += data.bname; extraAddress += data.bname;
console.log(extraAddress)
} }
if (data.buildingName !== "") { if (data.buildingName !== "") {
extraAddress += extraAddress +=
......
...@@ -7,24 +7,17 @@ import catchError from '../utils/catchErrors'; ...@@ -7,24 +7,17 @@ import catchError from '../utils/catchErrors';
import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap'; import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap';
function ProductsList({ match }) { function ProductsList({ match }) {
const INIT_STATUS = { indexOfFirst: 0, indexOfLast: 10 }
const [search, setSearch] = useState({ word: '' }) const [search, setSearch] = useState({ word: '' })
const [sortingName, setSortingName] = useState('정렬')
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 [currentPage, setCurrentPage] = useState(1); const [status, setStatus] = useState(INIT_STATUS)
const [postsPerPage, setPostsPerPage] = useState(6); const [currentPage, setCurrentPage] = useState(1)
const [error, setError] = useState('') const [error, setError] = useState('')
const indexOfLast = currentPage * postsPerPage;
const indexOfFirst = indexOfLast - postsPerPage;
const searchref = useRef(null) const searchref = useRef(null)
const per = 10;
const [sortingName, setSortingName] = useState('정렬')
function currentPosts(tmp) {
let currentPosts = 0;
currentPosts = tmp.slice(indexOfFirst, indexOfLast);
return currentPosts;
}
useEffect(() => { useEffect(() => {
setMainCategory(match.params.main.toUpperCase()) setMainCategory(match.params.main.toUpperCase())
...@@ -36,6 +29,16 @@ function ProductsList({ match }) { ...@@ -36,6 +29,16 @@ function ProductsList({ match }) {
getProductlist() getProductlist()
}, [mainCategory]) }, [mainCategory])
useEffect(() => {
setStatus({ indexOfFirst: (currentPage - 1) * per, indexOfLast: currentPage * per })
}, [currentPage])
function currentPosts(items) {
let currentPosts = '';
currentPosts = items.slice(status.indexOfFirst, status.indexOfLast);
return currentPosts
}
function handleChange(event) { function handleChange(event) {
setSearch({ word: event.target.value }) setSearch({ word: event.target.value })
} }
...@@ -45,8 +48,8 @@ function ProductsList({ match }) { ...@@ -45,8 +48,8 @@ function ProductsList({ match }) {
try { try {
setError('') setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} finally { } finally {
...@@ -59,7 +62,6 @@ function ProductsList({ match }) { ...@@ -59,7 +62,6 @@ function ProductsList({ match }) {
setError('') setError('')
const response = await axios.get(`/api/categories/sub/${mainCategory}`) const response = await axios.get(`/api/categories/sub/${mainCategory}`)
setSubCategory(Object.values(response.data)[0]) setSubCategory(Object.values(response.data)[0])
console.log("object value=", Object.values(response.data));
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -70,6 +72,7 @@ function ProductsList({ match }) { ...@@ -70,6 +72,7 @@ function ProductsList({ match }) {
setError('') setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -81,55 +84,55 @@ function ProductsList({ match }) { ...@@ -81,55 +84,55 @@ function ProductsList({ match }) {
console.log("thisispurchase") console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.purchase > b.purchase) { if (a.purchase > b.purchase) {
return -1; return -1;
} }
if (a.purchase < b.purchase) { if (a.purchase < b.purchase) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("인기상품") setSortingName("인기상품")
} else if(method === "newest"){ } else if (method === "newest") {
console.log("thisisnewest") console.log("thisisnewest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.createdAt > b.createdAt) { if (a.createdAt > b.createdAt) {
return -1; return -1;
} }
if (a.createdAt < b.createdAt) { if (a.createdAt < b.createdAt) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("신상품") setSortingName("신상품")
} else if(method === "lowest"){ } else if (method === "lowest") {
console.log("thisislowest") console.log("thisislowest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return 1; return 1;
} }
if (a.price < b.price) { if (a.price < b.price) {
return -1; return -1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("낮은가격") setSortingName("낮은가격")
} else { } else {
console.log("thisispurchase") console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return -1; return -1;
} }
if (a.price < b.price) { if (a.price < b.price) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("높은가격") setSortingName("높은가격")
} }
} }
...@@ -137,10 +140,10 @@ function ProductsList({ match }) { ...@@ -137,10 +140,10 @@ function ProductsList({ match }) {
async function handleSubname(e) { async function handleSubname(e) {
const subname = e.target.name const subname = e.target.name
try { try {
console.log("first test!!!!!!!!") setError('')
const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`) const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`)
console.log("subname response data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -154,7 +157,6 @@ function ProductsList({ match }) { ...@@ -154,7 +157,6 @@ function ProductsList({ match }) {
return ( return (
<Container> <Container>
{console.log(productlist)}
<style type="text/css"> <style type="text/css">
{` {`
a, a:hover, a:active { a, a:hover, a:active {
...@@ -164,10 +166,22 @@ function ProductsList({ match }) { ...@@ -164,10 +166,22 @@ function ProductsList({ match }) {
.btn { .btn {
background-color: #CDC5C2; background-color: #CDC5C2;
border-color: #CDC5C2; border-color: #CDC5C2;
border-radius: 0;
} }
.btn:hover { .btn:hover, .btn:focus {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
box-shadow: 0 0 0 0;
}
.btn-primary:not(:disabled):not(.disabled).active, .btn-primary:not(:disabled):not(.disabled):active, .show>.btn-primary.dropdown-toggle {
background-color: #91877F;
border-color: #91877F;
}
.show>.btn-primary.dropdown-toggle:focus {
box-shadow: 0 0 0 0;
}
.dropdown-item {
color: #91877F;
} }
.dropdown-item:hover, .dropdown-item:active { .dropdown-item:hover, .dropdown-item:active {
background-color: #91877F; background-color: #91877F;
...@@ -179,8 +193,8 @@ function ProductsList({ match }) { ...@@ -179,8 +193,8 @@ function ProductsList({ match }) {
<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"> <div className="text-center">
<ButtonGroup className="m-3" variant="outline-light secondary" style={{ display: "inline-block" }}> <ButtonGroup className="m-3" style={{ display: "inline-block" }}>
{subCategory.map(el => (<Button className="m-1" variant="secondary" name={el} onClick={handleSubname}>{el}</Button>))} {subCategory.map(el => (<Button className="m-1" name={el} onClick={handleSubname}>{el}</Button>))}
</ButtonGroup> </ButtonGroup>
</div> </div>
</Col> </Col>
...@@ -188,7 +202,7 @@ function ProductsList({ match }) { ...@@ -188,7 +202,7 @@ function ProductsList({ match }) {
<Row className="justify-content-end mx-0 mt-5 mb-3"> <Row className="justify-content-end mx-0 mt-5 mb-3">
<Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2"> <Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2">
<FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} /> <FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2 mr-2"> <Button type="submit" className="px-2 mr-2">
<img src="/icon/search.svg" width="20" height="20" /> <img src="/icon/search.svg" width="20" height="20" />
</Button> </Button>
</Form> </Form>
...@@ -204,7 +218,7 @@ function ProductsList({ match }) { ...@@ -204,7 +218,7 @@ function ProductsList({ match }) {
</Row> </Row>
<Row md={8} sm={12} className="justify-content-center m-2"> <Row md={8} sm={12} className="justify-content-center m-2">
{productlist.length > 0 ? {productlist.length > 0 ?
productlist.map(pro => ( currentPosts(productlist).map(pro => (
<Link to={{ <Link to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
...@@ -228,6 +242,7 @@ function ProductsList({ match }) { ...@@ -228,6 +242,7 @@ function ProductsList({ match }) {
) )
} }
</Row> </Row>
{productlist.length != 0 ? <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> : ''}
</Container> </Container>
) )
} }
......
...@@ -9,7 +9,6 @@ const imageUpload = upload.fields([ ...@@ -9,7 +9,6 @@ const imageUpload = upload.fields([
]) ])
const regist = async (req, res) => { const regist = async (req, res) => {
console.log("req.body=", req.body)
try { try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0] const main_img = req.files['main_image'][0]
...@@ -24,7 +23,6 @@ const regist = async (req, res) => { ...@@ -24,7 +23,6 @@ const regist = async (req, res) => {
}).save() }).save()
res.json(newProduct) res.json(newProduct)
} catch (error) { } catch (error) {
console.log(error)
res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.') res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.')
} }
} }
...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => { ...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -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 }) res.json({ bestProduct, newProduct })
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
...@@ -69,7 +65,6 @@ const getlist = (req, res) => { ...@@ -69,7 +65,6 @@ const getlist = (req, res) => {
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
console.log("req=", req.query.product)
try { try {
if (req.query.product) { if (req.query.product) {
const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } }) const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } })
...@@ -89,13 +84,11 @@ const categoryId = async (req, res, next, category) => { ...@@ -89,13 +84,11 @@ const categoryId = async (req, res, next, category) => {
} }
const subname = async (req, res) => { const subname = async (req, res) => {
console.log("req.query", req.query)
try { try {
const findSubname = await Product.find({ sub_category: req.query.subname }) const findSubname = await Product.find({ sub_category: req.query.subname })
console.log("findSubname111=", findSubname)
res.send(findSubname) res.send(findSubname)
} catch (error) { } catch (error) {
res.send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
...@@ -111,11 +104,12 @@ const plusPurchase = async (req, res) => { ...@@ -111,11 +104,12 @@ const plusPurchase = async (req, res) => {
const stock = product.stock const stock = product.stock
await Product.updateOne( await Product.updateOne(
{ _id: products[i].productId._id }, { _id: products[i].productId._id },
{ $set: {
{ $set:
purchase: count + purchase, {
stock: stock - count purchase: count + purchase,
} stock: stock - count
}
} }
) )
} }
...@@ -125,4 +119,17 @@ const plusPurchase = async (req, res) => { ...@@ -125,4 +119,17 @@ const plusPurchase = async (req, res) => {
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase } const deletePro = async (req, res) => {
\ No newline at end of file const pro_id = req.query.pro_id
try {
const productOne = await Product.findById(pro_id)
if (productOne) {
await Product.remove({ _id: pro_id })
}
res.send('삭제 성공')
} catch (error) {
res.status(500).send('삭제할 상품을 찾지 못하거나 삭제 중 문제가 발생했습니다.')
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase, deletePro }
\ No newline at end of file
...@@ -22,7 +22,9 @@ router.route('/getproduct/sub') ...@@ -22,7 +22,9 @@ router.route('/getproduct/sub')
router.route('/pluspurchase') router.route('/pluspurchase')
.post(productCtrl.plusPurchase) .post(productCtrl.plusPurchase)
router.route('/delete')
.delete(productCtrl.deletePro)
router.param('category', productCtrl.categoryId) router.param('category', productCtrl.categoryId)
// router.param('subname',productCtrl.subcategoryId)
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