Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 32 additions & 12 deletions src/apis/api.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { instance, instanceWithToken } from './axios';
import { instance, instanceWithToken } from "./axios";

// Account 관련 API들
export const signIn = async (data) => {
Expand Down Expand Up @@ -64,7 +64,7 @@ export const updatePost = async (id, data, navigate) => {
// 과제!!
export const deletePost = async (id, navigate) => {
const response = await instanceWithToken.delete(`/post/${id}/`);
if(response.status === 204) {
if (response.status === 204) {
console.log("DELETE SUCCESS");
navigate(-1);
} else {
Expand All @@ -74,7 +74,17 @@ export const deletePost = async (id, navigate) => {

// 과제!!
export const likePost = async (postId) => {

try {
const response = await instanceWithToken.post(`/post/${postId}/like/`);
if (response.status === 200) {
console.log("LIKE SUCCESS");
window.location.reload();
} else {
console.log("[ERROR] error while liking post");
}
} catch (error) {
console.log(error);
}
};

// Tag 관련 API들
Expand All @@ -100,17 +110,21 @@ export const getComments = async (postId) => {
};

export const createComment = async (data) => {
const response = await instanceWithToken.post("/comment/", data);
if (response.status === 201) {
console.log("COMMENT SUCCESS");
window.location.reload(); // 새로운 코멘트 생성시 새로고침으로 반영
} else {
console.log("[ERROR] error while creating comment");
try {
const response = await instanceWithToken.post("/comment/", data);
if (response.status === 201) {
console.log("COMMENT SUCCESS");
window.location.reload(); // 새로운 코멘트 생성시 새로고침으로 반영
} else {
console.log("[ERROR] error while creating comment");
}
} catch (error) {
console.log(error);
}
};

export const updateComment = async (id, data) => {
const response = await instanceWithToken.put(`/comment/${id}/`, data);// 혹시 patch로 구현했다면 .patch
const response = await instanceWithToken.put(`/comment/${id}/`, data); // 혹시 patch로 구현했다면 .patch
if (response.status === 200) {
console.log("COMMENT UPDATE SUCCESS");
window.location.reload();
Expand All @@ -121,5 +135,11 @@ export const updateComment = async (id, data) => {

// 과제 !!
export const deleteComment = async (id) => {

};
const response = await instanceWithToken.delete(`/comment/${id}/`);
if (response.status === 204) {
console.log("DELETE SUCCESS");
window.location.reload(); // 코멘트 삭제시 새로고침으로 반영
} else {
console.log("[ERROR] error while deleting comment");
}
};
21 changes: 11 additions & 10 deletions src/apis/axios.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import axios from "axios";
import { getCookie } from "../utils/cookie";

// baseURL, credential, 헤더 세팅
axios.defaults.baseURL = 'http://localhost:8000/api';
// baseURL, credential, 헤더 세팅
axios.defaults.baseURL = "http://localhost:8000/api";
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.common['X-CSRFToken'] = getCookie('csrftoken');
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.common["X-CSRFToken"] = getCookie("csrftoken");

// 누구나 접근 가능한 API들
// 누구나 접근 가능한 API들
export const instance = axios.create();

// Token 있어야 접근 가능한 API들 - 얘는 토큰을 넣어줘야 해요
Expand All @@ -16,13 +16,14 @@ export const instanceWithToken = axios.create();
// instanceWithToken에는 쿠키에서 토큰을 찾고 담아줍시다!
instanceWithToken.interceptors.request.use(
// 요청을 보내기전 수행할 일
// 사실상 이번 세미나에 사용할 부분은 이거밖에 없어요
// 사실상 이번 세미나에 사용할 부분은 이거밖에 없어요
(config) => {
const accessToken = getCookie('access_token');
const accessToken = getCookie("access_token");

if (!accessToken) {
// token 없으면 리턴
return;
alert("Please login first.");
throw new Error("No Token");
} else {
// token 있으면 헤더에 담아주기 (Authorization은 장고에서 JWT 토큰을 인식하는 헤더 key)
config.headers["Authorization"] = `Bearer ${accessToken}`;
Expand All @@ -40,7 +41,7 @@ instanceWithToken.interceptors.request.use(

instanceWithToken.interceptors.response.use(
(response) => {
// 서버 응답 데이터를 프론트에 넘겨주기 전 수행할 일
// 서버 응답 데이터를 프론트에 넘겨주기 전 수행할 일
console.log("Interceptor Response!!");
return response;
},
Expand All @@ -49,4 +50,4 @@ instanceWithToken.interceptors.response.use(
console.log("Response Error!!");
return Promise.reject(error);
}
);
);
132 changes: 78 additions & 54 deletions src/components/Comment/CommentElement.jsx
Original file line number Diff line number Diff line change
@@ -1,59 +1,83 @@
import { useState, useEffect } from "react";
import { updateComment, getUser } from "../../apis/api";
import { getCookie } from "../../utils/cookie";

const CommentElement = (props) => {
const { comment, handleCommentDelete, postId } = props;
const [content, setContent] = useState(comment.content);
const [isEdit, setIsEdit] = useState(false);

const [onChangeValue, setOnChangeValue] = useState(content); // 수정 취소 시 직전 content 값으로 변경을 위한 state

// comment created_at 전처리
const date = new Date(comment.created_at);
const year = date.getFullYear();
let month = date.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
let day = date.getDate();
day = day < 10 ? `0${day}` : day;

const handleEditComment = () => { // add api call for editing comment
setContent(onChangeValue);
setIsEdit(!isEdit);
console.log({
post: postId,
comment: comment.id,
content: content
});
};

useEffect(() => { // add api call to check if user is the author of the comment
}, []);

return (
<div className="w-full flex flex-row justify-between items-center mb-5">
<div className="w-3/4 flex flex-col gap-1">
{isEdit ? (
<input className="input mb-2" value={onChangeValue} onChange={(e) => setOnChangeValue(e.target.value)} />
) : (
<p className="text-lg">{content}</p>
)}

<span className="text-base text-gray-300">{year}.{month}.{day}</span>
</div>

<div className="flex flex-row items-center gap-3">
{isEdit ? (
<>
<button onClick={() => { setIsEdit(!isEdit); setOnChangeValue(content); }}>취소</button>
<button onClick={handleEditComment}>완료</button>
</>
) : (
<>
<button onClick={() => handleCommentDelete(comment.id)}>삭제</button>
<button onClick={() => setIsEdit(!isEdit)}>수정</button>
</>
)}
</div>
</div>
);
const { comment, handleCommentDelete, postId } = props;
const [content, setContent] = useState(comment.content);
const [isEdit, setIsEdit] = useState(false);
const [user, setUser] = useState(null); // state for user

const [onChangeValue, setOnChangeValue] = useState(content); // 수정 취소 시 직전 content 값으로 변경을 위한 state

// comment created_at 전처리
const date = new Date(comment.created_at);
const year = date.getFullYear();
let month = date.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
let day = date.getDate();
day = day < 10 ? `0${day}` : day;

const handleEditComment = async () => {
await updateComment(comment.id, { content: onChangeValue });
setIsEdit(!isEdit);
};

// get user info
useEffect(() => {
if (getCookie("access_token")) {
const getUserAPI = async () => {
const user = await getUser();
setUser(user);
};
getUserAPI();
}
}, []);

return (
<div className="w-full flex flex-row justify-between items-center mb-5">
<div className="w-3/4 flex flex-col gap-1">
{isEdit ? (
<input
className="input mb-2"
value={onChangeValue}
onChange={(e) => setOnChangeValue(e.target.value)}
/>
) : (
<p className="text-lg">{content}</p>
)}

<span className="text-base text-gray-300">
{year}.{month}.{day}
</span>
</div>

<div className="flex flex-row items-center gap-3">
{user?.id === comment.author.id ? (
isEdit ? (
<>
<button
onClick={() => {
setIsEdit(!isEdit);
setOnChangeValue(content);
}}
>
취소
</button>
<button onClick={handleEditComment}>완료</button>
</>
) : (
<>
<button onClick={() => handleCommentDelete(comment.id)}>
삭제
</button>
<button onClick={() => setIsEdit(!isEdit)}>수정</button>
</>
)
) : null}
{}
</div>
</div>
);
};
export default CommentElement;
52 changes: 27 additions & 25 deletions src/components/Comment/index.jsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,38 @@
import { useState } from "react";
import comments from "../../data/comments"; // dummy data
import { useState, useEffect } from "react";
import CommentElement from "./CommentElement";
import { getComments, createComment, deleteComment } from "../../apis/api";

const Comment = ({ postId }) => {
const [commentList, setCommentList] = useState(comments); // state for comments
const [commentList, setCommentList] = useState([]); // state for comments
const [newContent, setNewContent] = useState(""); // state for new comment

const handleCommentSubmit = (e) => {
// get comments of the post
useEffect(() => {
const getCommentsAPI = async () => {
const comments = await getComments(postId);
setCommentList(comments);
}
getCommentsAPI();
}, [postId]);

const handleCommentSubmit = async (e) => {
e.preventDefault();
setCommentList([ // TODO: add api call for creating comment
...commentList,
{
id: commentList.length + 1,
content: newContent,
created_at: new Date().toISOString(),
post: postId,
author: {
id: 1,
username: "user1"
}
}
]);
console.log({
post: postId,
content: newContent
});
// add new comment to the list
await createComment({post: postId , content: newContent});
// reset newContent
setNewContent("");
// comments will be updated by reloading the page in createComment function
};

const handleCommentDelete = (commentId) => {
console.log("comment: ", commentId);
setCommentList(commentList.filter((comment) => comment.id !== commentId)); // TODO: add api call for deleting comment
const handleCommentDelete = async (commentId) => {
const confirmDelete = window.confirm("정말 삭제하시겠습니까?");
if(!confirmDelete) return;

try {
await deleteComment(commentId);
} catch (error) {
console.error(error);
}
};

return (
Expand All @@ -50,4 +52,4 @@ const Comment = ({ postId }) => {
);
};

export default Comment;
export default Comment;
Loading