Commit 3ed89fa4 authored by Kim, Subin's avatar Kim, Subin
Browse files

공지사항 삭제, 수정기능 구현중

parent 1322417b
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
"start": "react-scripts start", "start": "react-scripts start",
"build": "react-scripts build", "build": "react-scripts build",
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject", "eject": "react-scripts eject"
}, },
"eslintConfig": { "eslintConfig": {
"extends": "react-app" "extends": "react-app"
......
import React, { useState, useContext } from 'react'; import React, { useContext } from 'react';
import { Card, Accordion, Col, AccordionContext, useAccordionToggle } from 'react-bootstrap'; import { Link } from 'react-router-dom';
import axios from 'axios';
import { Card, Accordion, Col, AccordionContext, useAccordionToggle, Button } from 'react-bootstrap';
import styled from 'styled-components'; import styled from 'styled-components';
const Text = styled(Card.Body)` const Text = styled(Card.Body)`
...@@ -11,7 +13,7 @@ const Text = styled(Card.Body)` ...@@ -11,7 +13,7 @@ const Text = styled(Card.Body)`
} }
` `
function Notice({ card_index, title, date, content }) { function Notice({ card_id, card_index, title, date, content, admin }) {
function ContextAwareToggle({ children, eventKey, callback }) { function ContextAwareToggle({ children, eventKey, callback }) {
const currentEventKey = useContext(AccordionContext); const currentEventKey = useContext(AccordionContext);
...@@ -44,6 +46,18 @@ function Notice({ card_index, title, date, content }) { ...@@ -44,6 +46,18 @@ function Notice({ card_index, title, date, content }) {
return new_date return new_date
} }
function remove (card_id) {
axios.delete(`/notices/${card_id}`)
.then(res => {
if (res.status === 404) return alert(res.data.error)
alert("삭제되었습니다!");
window.location.reload();
})
.catch(err => {
alert(err.error)
});
}
return ( return (
<Card className="w-100"> <Card className="w-100">
<Card.Header className="row flex-row py-3"> <Card.Header className="row flex-row py-3">
...@@ -53,9 +67,16 @@ function Notice({ card_index, title, date, content }) { ...@@ -53,9 +67,16 @@ function Notice({ card_index, title, date, content }) {
<Col md={2} xs={4} className="p-0" >{dateForm(date)}</Col> <Col md={2} xs={4} className="p-0" >{dateForm(date)}</Col>
</Card.Header> </Card.Header>
<Accordion.Collapse eventKey={card_index + 1}> <Accordion.Collapse eventKey={card_index + 1}>
<Text>{content.split("\n").map((i, key) => { <Text>
return <div key={key}>{i}</div>; {content.split("\n").map((i, key) => {
})}</Text> return <div key={key}>{i}</div>;
})}
{admin === "admin" ? (
<div className="d-flex justify-content-end">
<Button variant="primary" size="sm" as={Link} to={`/write/revise/${card_id}`}>수정</Button>
<Button variant="danger" size="sm" onClick={() => remove(card_id)}>삭제</Button>
</div>) : null}
</Text>
</Accordion.Collapse> </Accordion.Collapse>
</Card > </Card >
) )
......
...@@ -14,6 +14,7 @@ function Apply(props) { ...@@ -14,6 +14,7 @@ function Apply(props) {
useEffect(() => { useEffect(() => {
getUser(); getUser();
}, []) }, [])
if (state.ok==="no") return <Redirect to="/" />; if (state.ok==="no") return <Redirect to="/" />;
if (state.ok==="ok") { if (state.ok==="ok") {
return <Redirect to={{ return <Redirect to={{
......
...@@ -2,8 +2,7 @@ import React, { useState, useEffect } from 'react'; ...@@ -2,8 +2,7 @@ import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import axios from 'axios'; import axios from 'axios';
import Table from 'react-bootstrap/Table' import { Container, Table } from 'react-bootstrap';
import { Container } from 'react-bootstrap';
import styled from 'styled-components'; import styled from 'styled-components';
const Ta = styled(Table)` const Ta = styled(Table)`
...@@ -26,7 +25,6 @@ margin-top: 0.5em; ...@@ -26,7 +25,6 @@ margin-top: 0.5em;
align-items: center; align-items: center;
margin: 10px; margin: 10px;
}; };
` `
function Check(props) { function Check(props) {
...@@ -52,7 +50,7 @@ function Check(props) { ...@@ -52,7 +50,7 @@ function Check(props) {
setState(true); setState(true);
} }
console.log(res.data); console.log(res.data);
const reserves=res.data.filter(function(item) { const reserves = res.data.filter(function(item) {
return item !== ''; return item !== '';
}); });
setReserve(reserves); setReserve(reserves);
......
...@@ -2,11 +2,10 @@ import React, { useState, useEffect } from 'react'; ...@@ -2,11 +2,10 @@ import React, { useState, useEffect } from 'react';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import axios from 'axios'; import axios from 'axios';
import { Link, Redirect } from 'react-router-dom'; import { Link, Redirect } from 'react-router-dom';
import { Container, Row, Col, Card, Accordion, Button } from 'react-bootstrap'; import { Container, Row, Col, Accordion, Button } from 'react-bootstrap';
import CARD from '../Components/Card'; import CARD from '../Components/Card';
function Notice() { function Notice() {
const [show, setShow] = useState(false);
const [notices, setNotices] = useState([]); const [notices, setNotices] = useState([]);
const [user, setUser] = useState({ role: "" }) const [user, setUser] = useState({ role: "" })
const [state, setState] = useState() const [state, setState] = useState()
...@@ -40,7 +39,7 @@ function Notice() { ...@@ -40,7 +39,7 @@ function Notice() {
axios.get(`/notices`) axios.get(`/notices`)
.then(res => { .then(res => {
if (res.status !== 201) { if (res.status !== 201) {
// alert(res.data.error); alert(res.data.error);
} }
setNotices(res.data); setNotices(res.data);
}) })
...@@ -58,7 +57,7 @@ function Notice() { ...@@ -58,7 +57,7 @@ function Notice() {
<h2 className="p-3 border-bottom d-flex justify-content-between">공지사항 {user.role === "admin" ? ( <h2 className="p-3 border-bottom d-flex justify-content-between">공지사항 {user.role === "admin" ? (
<Button as={Link} to="/write"> 작성</Button>) : null}</h2> <Button as={Link} to="/write"> 작성</Button>) : null}</h2>
<Accordion> <Accordion>
{notices.map((notice, index) => <CARD card_index={index} title={notice.notice_title} date={notice.post_date} content={notice.notice_content} /> {notices.map((notice, index) => <CARD card_id={notice._id} card_index={index} title={notice.notice_title} date={notice.post_date} content={notice.notice_content} admin={user.role} />
)} )}
</Accordion> </Accordion>
</Col> </Col>
......
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import * as Yup from 'yup'; import * as Yup from 'yup';
import axios from 'axios'; import axios from 'axios';
import { Container, Row, Col, Button } from 'react-bootstrap'; import { Container, Row, Col, Button } from 'react-bootstrap';
import { Field, Formik } from 'formik'; import { Field, Formik } from 'formik';
function Write() { function Write({ match }) {
const [submitData, setSubmitData] = useState(false);
const [state, setState] = useState(false); const [state, setState] = useState(false);
const [revision, setRevision] = useState({ title: '', content: '' });
// const [isadmin, setIsadmin] = useState({ok:""});
// const [user, setUser] = useState({ role: "" })
// if (isadmin.ok==="no") return <Redirect to="/" />;
useEffect(() => {
getOne(match.params.id)
}, [])
if (state) { if (state) {
return <Redirect to="/notice" />; return <Redirect to="/notice" />;
} }
function getOne (id) {
if (id) {
axios.get(`/notices/${id}`)
.then(res => {
if (res.status !== 201) {
alert(res.data.error);
}
setRevision({ title: res.data.notice_title, content: res.data.notice_content })
})
.catch(err => {
alert(err.error)
});
}
};
// function putData (match, revision) {
// if (!match.params.id) return { title: '', content: '' }
// else return { title: revision.notice_title, content: revision.notice_content }
// };
// function acheck() {
// axios.get(`/users/${localStorage.getItem('_id')}`, {
// headers: { authorization: localStorage.getItem('token') },
// })
// .then(res => {
// if (res.status !== 201) {
// alert(res.data.error);
// localStorage.clear();
// setIsadmin({ok:"no"});
// }
// if (res.data.role == "admin") {
// setUser(res.data)
// }
// }).catch(err => {
// alert(err.error)
// });
// }
return ( return (
<div> <div>
<Menu /> {console.log("revision", revision.title, revision.content)}
<Menu/>
<Container fluid> <Container fluid>
<Row className="justify-content-center"> <Row className="justify-content-center">
<Col md={5} xs={11} className="pt-3" > <Col md={5} xs={11} className="pt-3" >
<Formik <Formik
initialValues={{ title: '', content: '' }} initialValues={{title: revision.title, content: revision.content}}
validationSchema={Yup.object({ validationSchema={Yup.object({
title: Yup.string() title: Yup.string()
.required('제목을 입력해주세요.'), .required('제목을 입력해주세요.'),
...@@ -28,19 +76,34 @@ function Write() { ...@@ -28,19 +76,34 @@ function Write() {
.required('내용을 입력해주세요.'), .required('내용을 입력해주세요.'),
})} })}
onSubmit={(values, { setSubmitting }) => { onSubmit={(values, { setSubmitting }) => {
axios({ if (!match.params.id) {
method: 'post', axios({
url: '/writes', method: 'post',
data: values, url: '/writes',
}).then(res => { data: values,
if (res.status === 404) return alert(res.data.error) }).then(res => {
alert("공지 등록이 완료되었습니다.") if (res.status === 404) return alert(res.data.error)
setState(true); alert("공지 등록이 완료되었습니다.")
}) setState(true);
.catch(err => { })
alert(err.error) .catch(err => {
}); alert(err.error)
});
} else {
axios({
method: 'put',
url: '/writes/${id}',
data: values,
})
.then(res => {
if (res.status === 404) return alert(res.data.error)
alert("공지 수정이 완료되었습니다.")
setState(true);
})
.catch(err => {
alert(err.error)
});
}
setTimeout(() => { setTimeout(() => {
setSubmitting(false); setSubmitting(false);
}, 400); // finish the cycle in handler }, 400); // finish the cycle in handler
...@@ -61,13 +124,13 @@ function Write() { ...@@ -61,13 +124,13 @@ function Write() {
{...getFieldProps('title')} {...getFieldProps('title')}
placeholder="제목" /> placeholder="제목" />
</div> </div>
{console.log(revision.title)}
<div className="form-group "> <div className="form-group">
<div className={touched.name && errors.name ? "text-danger" : ""}>내용</div> <div className={touched.name && errors.name ? "text-danger" : ""}>내용</div>
<Field as="textarea" rows={8} style={{ "min-width": "100%" }} <Field as="textarea" rows={8} style={{ "min-width": "100%" }}
{...getFieldProps('content')} /> {...getFieldProps('content')} />
</div> </div>
<Button className="mb-2" variant="dark" type="submit" disabled={isSubmitting}>공지 등록</Button> <Button className="mb-2" variant="dark" type="submit" disabled={isSubmitting}>{match.params.id ? "공지 수정" : "공지 등록"}</Button>
</form> </form>
)} )}
</Formik> </Formik>
......
...@@ -33,6 +33,7 @@ ReactDOM.render( ...@@ -33,6 +33,7 @@ ReactDOM.render(
<Route path="/change" component={Change} /> <Route path="/change" component={Change} />
<Route path="/apply/:id" component={Apply} /> <Route path="/apply/:id" component={Apply} />
<Route path="/check/:id" component={Check} /> <Route path="/check/:id" component={Check} />
<Route path="/write/revise/:id" component={Write} />
<Route path="/write" component={Write} /> <Route path="/write" component={Write} />
<Route path="/notice" component={Notice} /> <Route path="/notice" component={Notice} />
<Route path="/acheck/:id" component={ACheck} /> <Route path="/acheck/:id" component={ACheck} />
......
...@@ -9,12 +9,33 @@ router.get('/', function (req, res, next) { ...@@ -9,12 +9,33 @@ router.get('/', function (req, res, next) {
res.status(201).json(notices); res.status(201).json(notices);
}) })
.catch((err) => { .catch((err) => {
console.error(err);
next(err); next(err);
}); });
// res.status(404).json({error:"없음."}) // res.status(404).json({error:"없음."})
res.status(201).json(notices); res.status(201).json(notices);
}); });
router.get('/:id', function (req, res, next) {
Notice.findOne({ _id: req.params.id }, function (err, notice) {
if (err) return res.status(500).json({ error: err });
console.log("FindOne", notice)
res.status(201).json(notice);
})
});
router.delete('/:id', function (req, res, next) {
Notice.findOne({ _id: req.params.id }, function (err, notice) {
if (err) return res.status(500).json({ error: err });
notice.remove()
.then(() => {
console.log();
res.status(201).json();
})
.catch((err) => {
console.error(err);
next(err);
});
})
});
module.exports = router; module.exports = router;
\ No newline at end of file
...@@ -25,4 +25,23 @@ router.post('/', function (req, res, next) { ...@@ -25,4 +25,23 @@ router.post('/', function (req, res, next) {
}); });
}); });
router.put('/:id', function (req, res, next) {
console.log('/writes put req.body', req.params)
Notice.findOne({ _id: req.params.id }, function (err, notice) {
if (err) return res.status(500).json({ error: err });
notice.notice_title = req.body.title + " (수정)";
notice.post_date = req.body.post_date;
notice.notice_content = req.body.content;
notice.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
});
});
module.exports = router; module.exports = 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