Skip to content

Commit

Permalink
[Fix] 커뮤니티기능 서버연결
Browse files Browse the repository at this point in the history
-바뀐 API주소 적용
-게시물 작성 POST할때 헤더에 TOKEN 넣어서 전송 Issue #84
  • Loading branch information
sinjw committed Sep 12, 2023
1 parent ea57823 commit 1199ff4
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 39 deletions.
64 changes: 42 additions & 22 deletions client/src/components/communityComponents/Comments.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,62 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import styled from "styled-components";
import axios from "axios";

const Comments = ({ postId }: { postId: number }) => {
const Comments = ({ boardId }: { boardId: number }) => {
///api/boards/{boardId}/comment/
interface CommentData {
id: number;
comments: string;
}
const [commentData, setCommentData] = useState<CommentData[]>(() => {
// 게시물별로 로컬 스토리지에서 댓글 데이터를 가져옵니다.
const storedData = localStorage.getItem(`commentData_${postId}`);
return storedData ? JSON.parse(storedData) : [];
});

const [commentData, setCommentData] = useState<CommentData[]>([]);
const [commentsValue, setCommentsValue] = useState("");
useEffect(() => {
// 게시물 ID를 기반으로 서버에서 댓글 데이터를 가져옵니다.
fetchCommentsFromServer();
}, [boardId]);

const fetchCommentsFromServer = async () => {
try {
const response = await axios.get(`/api/boards/${boardId}/comment`);
setCommentData(response.data);
} catch (error) {
console.error("댓글 데이터를 가져오는 중 오류 발생:", error);
}
};

const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setCommentsValue(e.target.value);
};

const handleClickSubmit = () => {
const authToken = localStorage.getItem("authToken"); // 로컬스토리지 토큰 가져오기
const handleClickSubmit = async () => {
if (commentsValue) {
const newCommentData: CommentData = {
id: new Date().getTime(),

comments: commentsValue,
};

// 댓글 데이터를 업데이트합니다.
setCommentData((prevCommentData) => [...prevCommentData, newCommentData]);

// 게시물 ID에 따라 로컬 스토리지에 댓글 데이터를 저장합니다.
localStorage.setItem(
`commentData_${postId}`,
JSON.stringify([...commentData, newCommentData])
);

// 댓글 입력창 초기화
setCommentsValue("");
try {
// 서버에 댓글 데이터를 POST합니다.
const response = await axios.post(
`/api/boards/${boardId}/comment`,
newCommentData,
{
headers: {
Authorization: authToken, // 토큰을 헤더에 추가
},
}
);
if (response.status === 201) {
// 서버에 성공적으로 데이터를 업로드한 경우
setCommentsValue("");
// 서버에서 업데이트된 댓글 목록을 다시 가져오기
fetchCommentsFromServer();
} else {
console.log("댓글 작성 실패:", response.data);
}
} catch (error) {
console.error("댓글 작성 중 오류 발생:", error);
}
}
};
// 보여지는 댓글 수 제한 및 더보기 버튼 클릭시 모든댓글이 보이도록 설정
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,24 @@ const StockDisscussion: React.FC = () => {
}
};
return (
<div>
<DisscussionContainer>
{StockDisscussions.map((el) => (
<DisscussionList>{el.korName}</DisscussionList>
))}
</div>
</DisscussionContainer>
);
};
export default StockDisscussion;
interface StockDiscussion {
id: number;
korName: string;
}
const DisscussionContainer = styled.div`
max-height: 600px;
`;
const DisscussionList = styled.div`
display: flex;
justify-content: space-around;
margin: 0 auto;
margin-top: 20px;
Expand Down
38 changes: 25 additions & 13 deletions client/src/components/communityComponents/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DotIcon } from "./IconComponent/Icon";
import axios from "axios";
import { useNavigate } from "react-router-dom";
const serverUrl =
"http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/boards";
"http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/api/boards";

const TimeLineComponent = () => {
const navigate = useNavigate();
Expand Down Expand Up @@ -39,7 +39,7 @@ const TimeLineComponent = () => {
setinputValue(e.target.value);
console.log(inputValue);
};

const authToken = localStorage.getItem("authToken"); // 로컬스토리지 토큰 가져오기
// 서브밋 버튼 클릭
const handleClickSubmit = async () => {
if (inputValue.length !== 0) {
Expand All @@ -54,7 +54,11 @@ const TimeLineComponent = () => {
};

try {
const response = await axios.post(`${serverUrl}`, newBoardData);
const response = await axios.post(`${serverUrl}`, newBoardData, {
headers: {
Authorization: authToken, // 토큰을 요청 헤더에 추가
},
});
if (response.status === 201) {
// 서버에 성공적으로 데이터를 업로드한 경우
alert("작성완료");
Expand Down Expand Up @@ -90,7 +94,11 @@ const TimeLineComponent = () => {
const handleDeleteClick = async (boardId: number) => {
// boardId로 수정
try {
const response = await axios.delete(`${serverUrl}/${boardId}`); // URL에 boardId 추가
const response = await axios.delete(`${serverUrl}/${boardId}`, {
headers: {
Authorization: `Bearer ${authToken}`, // 토큰을 헤더에 추가
},
}); // URL에 boardId 추가
if (response.status === 200) {
// 삭제 성공 처리
alert("삭제되었습니다");
Expand Down Expand Up @@ -132,12 +140,16 @@ const TimeLineComponent = () => {
<DropDownClose onClick={handleSetOpenDropDown}>
<p>{timeLineText.close}</p>
</DropDownClose>
<DropdownInput
type="text"
placeholder="이곳에 작성해 주세요"
value={inputValue}
onChange={handleOnChange}
></DropdownInput>
{authToken === null || undefined ? (
<div>로그인해주세요</div>
) : (
<DropdownInput
type="text"
placeholder="이곳에 작성해 주세요"
value={inputValue}
onChange={handleOnChange}
></DropdownInput>
)}

<SubmitButton onClick={handleClickSubmit}>Submit</SubmitButton>
</>
Expand Down Expand Up @@ -169,7 +181,7 @@ const TimeLineComponent = () => {
<br />
{el.content}
</BoardText>
<Comments postId={el.boardId}></Comments>
<Comments boardId={el.boardId}></Comments>
</BoardTextArea>
))
)}
Expand Down Expand Up @@ -276,7 +288,7 @@ const SubmitButton = styled.button`
//게시판 전체 영역
const BoardArea = styled.div`
text-align: center;
max-height: 600px;
margin-top: 25px;
width: 90%;
`;
Expand All @@ -293,6 +305,7 @@ const BoardTextAreaNoText = styled.div`
`;
const BoardTextArea = styled.div`
width: 80%;
padding-bottom: 10px;
border-radius: 20px 20px;
border: 1px solid#40797c;
Expand All @@ -312,7 +325,6 @@ const TimeLine = styled.div`
flex-direction: column;
align-content: space-around;
flex-wrap: wrap;
max-height:600px;
`;
//게시글 삭제
const Delete = styled.div`
Expand Down
1 change: 1 addition & 0 deletions client/src/models/stateProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export interface StateProps {
companyId: number;
stockOrderVolume: number;
decisionWindow: boolean;
login: number;
}
5 changes: 3 additions & 2 deletions client/src/page/TabPages/MarketInfoPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const MarketInfo: React.FC<Props> = () => {
setTabStyle(number);
};
return (
<div>
<MarketContainer>
<style>
@import
url('https://fonts.googleapis.com/css2?family=Jua&family=Noto+Sans+KR:wght@500&display=swap');
Expand Down Expand Up @@ -42,7 +42,7 @@ const MarketInfo: React.FC<Props> = () => {
{selectedTab === "market" && <MarketSummary />}
{selectedTab === "stockList" && <MarketStockList />}
</div>
</div>
</MarketContainer>
);
};

Expand All @@ -53,6 +53,7 @@ const MarketInfoText = {
};
// **스타일 옮기기

const MarketContainer = styled.div``;
const TabStyle = styled.div`
cursor: pointer;
`;
Expand Down

0 comments on commit 1199ff4

Please sign in to comment.