Skip to content

Commit

Permalink
refactor[JustOneBite#53]: Write페이지 작성완료
Browse files Browse the repository at this point in the history
  • Loading branch information
dbwoflaqnzo3 committed Mar 3, 2025
1 parent a5291cf commit 60b3139
Show file tree
Hide file tree
Showing 7 changed files with 321 additions and 34 deletions.
Empty file.
133 changes: 133 additions & 0 deletions student/app/mainPage/helpPage/edit/detail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useState , useEffect } from "react";
import EditForm from './editForm';


const DetailPage = () => {
const searchParams = useSearchParams();
const postId = searchParams.get("postId");
const title = searchParams.get("title");

const [status , setStatus] = useState(null);
const [content , setContent] = useState('');
const [category , setCategory] = useState('');

const [answer , setAnswer] = useState('');
const [loading , setLoading] = useState(true);

// 렌더링이 될때 get요청
useEffect(()=>{
const fetchPostData = async () => {
try{
const res = await fetch(`/api/posts/${postId}`);
if(!res.ok){
throw new Error('Failed to fetch data');
}
const postData = await res.json();

// console.log(postData);

setStatus(postData.post.status);
setContent(postData.post.content);
setCategory(postData.post.category);
setAnswer(postData.post.answer);
} catch (err){
console.error('Error fetching post Data:', err);
} finally {
setLoading(false);
}
};

if(postId){
fetchPostData();
}

}, [postId])


// 버튼을 누렀을때 post요청
const handleEditClick = async (e) => {
e.preventDefault();

try {
const response = await fetch('/api/posts/updatePost', {
method: 'POST', // 또는 PUT 요청 사용 가능
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
postId,
title,
category,
content,
status: status, // 상태도 함께 전송
}),
});

if (response.ok) {
alert('수정된 내용이 저장되었습니다.');
} else {
console.error('수정 요청에 실패했습니다.');
}
} catch (error) {
console.error('서버와 연결하는 중 오류가 발생했습니다.', error);
}
}

const handleDeleteClick = async (e) => {
e.preventDefault();

try {
const response = await fetch('/api/posts/updatePost', {
method: 'Delete', // 또는 PUT 요청 사용 가능
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
postId,
title,
category,
content,
status: status, // 상태도 함께 전송
}),
});

if (response.ok) {
alert('수정된 내용이 삭제된거 처럼되었습니다.');
} else {
console.error('수정 요청에 실패했습니다.');
}
} catch (error) {
console.error('서버와 연결하는 중 오류가 발생했습니다.', error);
}
}


const handleCategoryChange = (e) => setCategory(e.target.value);
const handleContentChange = (e) => setContent(e.target.value);



return (
<div>
<h1>고객센터 - 글수정</h1>

{/* Form 컴포넌트에 필요한 props 전달 */}
<EditForm
postId={postId}
title={title}
category={category}
content={content}
status={status}
answer={answer}
onCategoryChange={handleCategoryChange}
onContentChange={handleContentChange}
onSubmit={handleEditClick}
onDelete={handleDeleteClick}
/>
</div>
);
};

export default DetailPage;
99 changes: 99 additions & 0 deletions student/app/mainPage/helpPage/edit/editForm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"use client";
import { posts } from '@/data'
import { useRouter } from "next/navigation"

const Form = ({postId, title, category, content, status, answer, onCategoryChange, onContentChange, onSubmit , onDelete}) => {
const data = posts[postId-1];
let router = useRouter();

const goSVPage = (e) => {
e.preventDefault();
router.push('/studentService');
}

return (
<form onSubmit={onSubmit}>
<div>
<div>
<label>제목</label>
<input
type="text"
value={title}
disabled={status === 1} // 제목은 수정 불가능
/>
</div>

<div>
<label>카테고리</label>
<select id="category" name="category"
required
value={category}
onChange={onCategoryChange}
disabled={status === 1}
>
<option value="로그인">로그인</option>
<option value="회원가입">회원가입</option>
<option value="기타">기타</option>
</select>
</div>

<div>
<label>등록자</label>
<input
type="text"
value={data.author}
disabled // 등록자는 수정 불가능
/>
</div>
</div>

{/* 여기가 추가부분 */}
<div>
<div>
<div>
<label>내용</label>
<textarea
value={content}
onChange={onContentChange} // 내용 수정 가능
disabled={status === 1} // 상태가 '처리완료'일 때는 수정 불가능
/>
</div>

<div>
<div>
<label>답변</label>
<span>{status === 0 ? '답변대기' : '처리완료'}</span>
</div>
<textarea
value={answer || '답변을 준비 중입니다.'}
disabled // 답변은 수정 불가능
/>
</div>
</div>
</div>


<div>
{status === 0 && (
<>
<button type="submit">
수정하기
</button>
<button type="button" onClick={onDelete}>
삭제하기
</button>
</>
)}
<button
type="button"
onClick={goSVPage}
>
목록보기
</button>
</div>
</form>

);
};

export default Form;
12 changes: 12 additions & 0 deletions student/app/mainPage/helpPage/edit/page.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<<<<<<< HEAD
"use client";
import { useSearchParams } from "next/navigation";
import { useState, useEffect } from "react";
Expand Down Expand Up @@ -121,3 +122,14 @@ const DetailPage = () => {
};

export default DetailPage;
=======
// 여기서 작성자를 토큰으로 받을예정
import DetailPage from "./detail"

export default function helpPageWrite() {

return(
<DetailPage/>
)
}
>>>>>>> 2eb536d (refactor[#53]: Write페이지 작성완료)
81 changes: 49 additions & 32 deletions student/app/mainPage/helpPage/listItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useState , useEffect } from 'react';



<<<<<<< HEAD
<<<<<<< HEAD
const ListItem = () => {
const [posts , setPosts] = useState([]);
Expand Down Expand Up @@ -68,51 +69,67 @@ const ListItem = () => {
export default ListItem;
=======
const listItem = () => {
=======
const ListItem = () => {
>>>>>>> 2eb536d (refactor[#53]: Write페이지 작성완료)
const [posts , setPosts] = useState([]);


useEffect(()=>{
const fetchPosts = async() => {
useEffect(() => {
const fetchPosts = async () => {
const res = await fetch('/api/posts');
const data = await res.json();
console.log(data)
if(res.ok){
setPosts(data.posts || [])

}else{
console.error('서버오류',res.message)
console.log(data);
if (res.ok) {
setPosts(data.posts || []);
} else {
console.error('서버 오류', res.message);
}
}

};
fetchPosts();
},[]);


}, []);

return (
<div className={styles.postList}>
{posts.map((post, index) => (
<div key={post.id} className={styles.navbar}>
<div className={styles.navbarItem}>{index + 1}</div> {/* 번호는 인덱스에 1을 더해서 표시 */}
<div className={styles.navbarItem}>{post.category}</div>
<Link
href={{
pathname: "/studentService/edit",
query: { postId: post.id, title: post.title },
}}

<div className={styles.header}>
<div className={styles.postItem}>번호</div>
<div className={styles.postItem}>카테고리</div>
<div className={styles.postItem}>제목</div>
<div className={styles.postItem}>등록자</div>
<div className={styles.postItem}>등록일</div>
<div className={styles.postItem}>상태</div>
</div>

{posts.map((post, index) => (
<div
key={post.id}
className={`${styles.postItems} ${post.category === '공지사항' ? styles.notice : styles.normalPost}`}
>
<div className={styles.navbarItem} style={{ cursor: "pointer", color: "blue" }}>
{post.title}
<div className={styles.postItem}>{index + 1}</div>
<div className={styles.postItem}>{post.category}</div>
<Link
href={{
pathname: "helpPage/edit",
// query: { postId: post.id, title: post.title },
}}
>
<div className={styles.postItem} style={{ cursor: "pointer", textDecoration: "none" }}>
{post.title}
</div>
</Link>
<div className={styles.postItem}>{post.author}</div>
<div className={styles.postItem}>{post.date}</div>
<div className={styles.postItem}>{post.status ? '처리완료' : '답변대기'}</div>
</div>
</Link>
<div className={styles.navbarItem}>{post.author}</div>
<div className={styles.navbarItem}>{post.date}</div>
<div className={styles.navbarItem}>{post.status ? '처리완료' : '답변대기'}</div>
</div>
))}
))}
</div>
);
};
};

<<<<<<< HEAD
export default listItem;
>>>>>>> 4dd0664 (feat[#53]: 글 카테고리 버튼 설정)
=======

export default ListItem;
>>>>>>> 2eb536d (refactor[#53]: Write페이지 작성완료)
Loading

0 comments on commit 60b3139

Please sign in to comment.