Skip to content
Snippets Groups Projects
Commit d964ea2c authored by 이현영's avatar 이현영
Browse files

Edit PostList

parent c06dc99c
Branches
No related tags found
No related merge requests found
import React, { useState, useEffect } from 'react';
import Diarybox from "./Diarybox.js";
import postService from '../Services/post'
import Pagination from "./Pagination.js";
const DiaryList = () => {
const total = 12;
const [postList, setpostList] = useState([]);
useEffect(() => {
const fetchPostList = async () => {
try {
const posts = await postService.getPostsByUser();
setpostList(posts);
console.log(postList);
} catch (error) {
console.error('Error fetching latest posts:', error);
}
};
fetchPostList();
}, []);
return(
<div className="container mx-auto px-5 flex flex-wrap flex-col sm:flex-row">
<Diarybox/>
<Diarybox/>
<Diarybox/>
<Diarybox/>
<Diarybox/>
<div className="w-full container mx-auto px-5 flex flex-wrap flex-col sm:flex-row">
<div className='w-full'>
{postList.map((post, index) => (
<Diarybox key={index} title={post.title} content={post.content} imgUrl={post.images} date={post.createdAt} />
))}
</div>
<Pagination total={total}/>
</div>
);
......
......@@ -4,22 +4,16 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-solid-svg-icons';
import GuestBook from './GuestBook.js'
const Diarybox = () => {
// const removeTags = (html) => {
// const doc = new DOMParser().parseFromString(html, 'text/html');
// let text = doc.body.textContent;
// text = text.replace(/\n\s*\n/g, '\n\n');
// return text || '';
// }
const Diarybox = ({title, date, content, imgUrl}) => {
const removeTags = (html) => {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// backend에서 fetch해야할 data들임 !!
const title = "어 그래그래 형은 웹시를 했어";
const content = "이 편지는 영국에서 최초로 시작되어 일년에 한바퀴를 돌면서 받는 사람에게 행운을 주었고 지금은 당신에게로 옮겨진 이 편지는 4일 안에 당신 곁을 떠나야 합니다. 이 편지를 포함해서 7통을 행운이 필요한 사람에게 보내 주셔야 합니다. 복사를 해도 좋습니다. 혹 미신이라 하실지 모르지만 사실입니다. 영국에서 HGXWCH이라는 사람은 1930년에 이 편지를 받았습니다. 그는 비서에게 복사해서 보내라고 했습니다. 며칠 뒤에 복권이 당첨되어 20억을 받았습니다. 어떤 이는 이 편지를 받았으나 96시간 이내 자신의 손에서 떠나야 한다는 사실을 잊었습니다. 그는 곧 사직되었습니다. 나중에야 이 사실을 알고 7통의 편지를 보냈는데 다시 좋은 직장을 얻었습니다. 미국의 케네디 대통령은 이 편지를 받았지만 그냥 버렸습니다. 결국 9일 후 그는 암살당했습니다. 기억해 주세요. 이 편지를 보내면 7년의 행운이 있을 것이고 그렇지 않으면 3년의 불행이 있을 것입니다. 그리고 이 편지를 버리거나 낙서를 해서는 절대로 안됩니다. 7통입니다. 이 편지를 받은 사람은 행운이 깃들것입니다. 힘들겠지만 좋은게 좋다고 생각하세요. 7년의 행운을 빌면서 미안하다 이거 보여주려고 어그로끌었다.. 나루토 사스케 싸움수준 ㄹㅇ실화냐? 진짜 세계관최강자들의 싸움이다.. 그찐따같던 나루토가 맞나? 진짜 나루토는 전설이다..진짜옛날에 맨날나루토봘는데 왕같은존재인 호카게 되서 세계최강 전설적인 영웅이된나루토보면 진짜내가다 감격스럽고 나루토 노래부터 명장면까지 가슴울리는장면들이 뇌리에 스치면서 가슴이 웅장해진다.. 그리고 극장판 에 카카시앞에 운석날라오는 거대한 걸 사스케가 갑자기 순식간에 나타나서 부숴버리곤 개간지나게 나루토가 없다면 마을을 지킬 자는 나밖에 없다 라며 바람처럼 사라진장면은 진짜 나루토처음부터 본사람이면 안울수가없더라 진짜 너무 감격스럽고 보루토를 최근에 알았는데 미안하다.. 지금20화보는데 진짜 나루토세대나와서 너무 감격스럽고 모두어엿하게 큰거보니 내가 다 뭔가 알수없는 추억이라해야되나 그런감정이 이상하게 얽혀있다.. 시노는 말이많아진거같다 좋은선생이고..그리고 보루토왜욕하냐 귀여운데 나루토를보는것같다 성격도 닮았어 그리고버루토에 나루토사스케 둘이싸워도 이기는 신같은존재 나온다는게 사실임?? 그리고인터닛에 쳐봣는디 이거 ㄹㅇㄹㅇ 진짜팩트냐?? 저적이 보루토에 나오는 신급괴물임?ㅡ 나루토사스케 합체한거봐라 진짜 ㅆㅂ 이거보고 개충격먹어가지고 와 소리 저절로 나오더라 ;; 진짜 저건 개오지는데.. 저게 ㄹㅇ이면 진짜 꼭봐야돼 진짜 세계도 파괴시키는거아니야 .. 와 진짜 나루토사스케가 저렇게 되다니 진짜 눈물나려고했다.. 버루토그라서 계속보는중인데 저거 ㄹㅇ이냐..? 하.. ㅆㅂ 사스케 보고싶다.. 진짜언제 이렇게 신급 최강들이 되었을까 옛날생각나고 나 중딩때생각나고 뭔가 슬프기도하고 좋기도하고 감격도하고 여러가지감정이 복잡하네.. 아무튼 나루토는 진짜 애니중최거명작임.."
const commentnum = 3; // 배열 length로 받아올수도 있음 comment 다같이 받아올 수 있음
const likes = 10;
const wroteDate = new Date('2023-09-23');
const imagePath = `${process.env.PUBLIC_URL}/areyoulike.png` // img의 경우 배열로 받아서 대표 [0]하면 될 것
// 여기까지
const imagePath = imgUrl ? imgUrl : `${process.env.PUBLIC_URL}/areyoulike.png`;
const [isOpened, setisOpened] = useState(false);
......@@ -39,10 +33,16 @@ const Diarybox = () => {
navigate("/main/view", { state: { isOpened: true } });
}
const summarizedContent = content.length > 200 ? content.substring(0, 200) + "..." : content;
const year = wroteDate.getFullYear();
const month = wroteDate.getMonth() + 1;
const day = wroteDate.getDate();
const summarizedContent = () => {
let summarizeContent = removeTags(content);
summarizeContent = summarizeContent.length > 200 ? summarizeContent.substring(0, 200) + "..." : summarizeContent;
return summarizeContent;
};
const today = new Date(date);
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const formattedDate = `${year}${month}${day}일`;
const userName = "박병하";
......@@ -95,7 +95,7 @@ const Diarybox = () => {
<div className="font-semibold text-gray-800">{title}</div>
</div>
</div>
<div className="text-sm leading-relaxed mb-2">{summarizedContent}</div>
<div className="text-sm leading-relaxed mb-2">{summarizedContent()}</div>
<div>
<div className="text-sm text-gray-500">{formattedDate} · {commentnum}개의 댓글 · <FontAwesomeIcon icon={faHeart} /> {likes}</div>
</div>
......
import React, { useMemo, useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import "./EditorToolbar.css";
......@@ -54,6 +55,12 @@ const Editor = () => {
return '';
}
const navigate = useNavigate();
const moveListPage = () => {
navigate('/main/diaryList');
};
const submitHandler = async () => {
if (!content.trim()) {
window.alert("작성되지 않은 내용이 있습니다.");
......@@ -66,7 +73,8 @@ const Editor = () => {
}
else {
await postService.createPost(title, content, imgUrl, mood, weather);
// TODO: 게시글 작성 완료 시 상세 페이지로 이동
// TODO: test 해봐야됨
moveListPage();
}
}
};
......
......@@ -11,6 +11,7 @@ const Paging = ({total}) => {
};
return (
<div>
<Pagination
activePage={page}
itemsCountPerPage={10}
......@@ -18,9 +19,12 @@ const Paging = ({total}) => {
pageRangeDisplayed={5}
prevPageText={""}
nextPageText={""}
innerClass="flex mb-4"
innerClass="flex justify-center items-center gap-3"
activeClass="text-base text-main-color font-semibold"
itemClass="text-sm"
onChange={handlePageChange}
/>
</div>
);
};
......
......@@ -5,7 +5,22 @@ import Calendar from './Calendar.js'
import './profile.css';
import postService from '../Services/post'
function profile(){
function Profile(){
const [latestPosts, setLatestPosts] = useState([]);
useEffect(() => {
const fetchPostList = async () => {
try {
const posts = await postService.getLatestPostsByUser();
setLatestPosts(posts);
} catch (error) {
console.error('Error fetching latest posts:', error);
}
};
fetchPostList();
}, []);
const userName = "박병하"; // fetch
const todayQuote = "중요한건 꺾이지 않는 마음"; // fetch
const numFeed = 5; // fetch
......@@ -74,7 +89,7 @@ function profile(){
<span className="text-sm text-blueGray-400">친구</span><span className="text-xl font-bold block uppercase tracking-wide text-blueGray-600">{numFeed}</span>
</div>
<div className="mr-4 p-3 text-center">
<span className="text-sm text-blueGray-400">작성글</span><span className="text-xl font-bold block uppercase tracking-wide text-blueGray-600">{numFeed}</span>
<span className="text-sm text-blueGray-400">작성글</span><span className="text-xl font-bold block uppercase tracking-wide text-blueGray-600">{friendNum}</span>
</div>
<div className="mr-4 p-3 text-center">
<span className="text-sm text-blueGray-400">가입</span><span className="text-xl font-bold block uppercase tracking-wide text-blueGray-600">D+{joinTime}</span>
......@@ -99,17 +114,17 @@ function profile(){
</div>
</div>
<div className='mt-5'>
<div className='mt-5 w-full'>
<div className='mb-2'>
<div className='mb-2'>최신글</div>
<hr width="100%"/>
</div>
<Diarybox/>
<Diarybox/>
<Diarybox/>
{latestPosts.map((post, index) => (
<Diarybox key={index} title={post.title} content={post.content} imgUrl={post.images} date={post.createdAt} />
))}
</div>
</div>
);
}
export default profile;
\ No newline at end of file
export default Profile;
\ No newline at end of file
......@@ -65,7 +65,7 @@ exports.createPost = async (title, content, images, mood, weather) => {
//게시글 수정
exports.updatePost = async(postId, updateData)=>{
const token = localStorage.getItem('jwt');
const token = localStorage.getItem('token');
try {
const response = await fetch(`http://3.38.218.162:3000/updatePost/${postId}`, {
method: 'PUT',
......@@ -83,7 +83,7 @@ exports.updatePost = async(postId, updateData)=>{
// 내 모든 게시글 조회
exports.getPostsByUser = async()=>{
const token = localStorage.getItem('jwt');
const token = localStorage.getItem('token');
try {
const response = await fetch('http://3.38.218.162:3000/posts', {
method: 'GET',
......@@ -111,7 +111,7 @@ exports.getPost = async(postId)=>{
// 게시글 삭제
exports.deletePost = async(postId)=>{
const token = localStorage.getItem('jwt');
const token = localStorage.getItem('token');
try {
const response = await fetch(`http://3.38.218.162:3000/deletePost/${postId}`, {
method: 'DELETE',
......@@ -126,8 +126,8 @@ exports.deletePost = async(postId)=>{
}
// 최신 게시물 3개 조회
exports.getLatestPostsByUser = async(postId)=>{
const token = localStorage.getItem('jwt');
exports.getLatestPostsByUser = async()=>{
const token = localStorage.getItem('token');
try {
const response = await fetch('http://3.38.218.162:3000/posts/latest', {
method: 'GET',
......@@ -135,6 +135,7 @@ exports.getLatestPostsByUser = async(postId)=>{
'Authorization': `Bearer ${token}`
}
});
return await response.json();
} catch (error) {
console.error('Error:', error);
......@@ -143,7 +144,7 @@ exports.getLatestPostsByUser = async(postId)=>{
// 특정 월의 감정 조회
exports.getEmotionsByMonth = async(year,month)=>{
const token = localStorage.getItem('jwt');
const token = localStorage.getItem('token');
try {
const response = await fetch(`http://3.38.218.162:3000/emotions/${year}/${month}`, {
method: 'GET',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment