Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge: develop to main merge #57

Merged
merged 16 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
5 changes: 3 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import ProfileEdit from "./pages/ProfileEdit";
import InterestEdit from "./pages/InterestEdit";
import QnaBoard from "./pages/QnaBoard";
import AnswerList from "./pages/AnswerList";

axios.defaults.baseURL = "http://3.36.247.28";
import MyPage from "./pages/Mypage";
import axiosInstance from "./api/AxiosInstance"; // Axios 인스턴스 가져오기

const queryClient = new QueryClient();

Expand All @@ -36,6 +36,7 @@ const App: React.FC = () => {
<Route path="/articles" element={<ArticleBoards />} />
<Route path="ticleQna" element={<QnaBoard />} />
<Route path="/ticleQna/:opinionId" element={<AnswerList />} />
<Route path="/mypage" element={<MyPage />} />
</Routes>
</Router>
</QueryClientProvider>
Expand Down
43 changes: 43 additions & 0 deletions src/api/AxiosInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import axios from "axios";

const axiosInstance = axios.create({
baseURL: "http://3.36.247.28/api/", // 직접 URL 지정
});

axiosInstance.interceptors.request.use((config) => {
const token = localStorage.getItem("token");

// 정규 표현식을 사용하여 /post/{id} 패턴 매칭
const excludedUrls = [
"/opinion",
"/home",
"/users/sign-up",
"/users/sign-in",
"/users/emailSend",
"/post", // 문자열로 /post 제외
/^\/post\/\d+$/, // 정규 표현식으로 /post/{id} 패턴 매칭
];

if (token) {
const isExcluded = excludedUrls.some((url) => {
if (typeof url === "string") {
return config.url === url;
} else if (url instanceof RegExp) {
return url.test(config.url || "");
}
return false;
});

if (token) {
if (config.url === "/users/logout") {
config.headers.Authorization = `${token}`;
} else if (!isExcluded) {
config.headers.Authorization = `Bearer ${token}`;
}
}
}

return config;
});

export default axiosInstance;
7 changes: 5 additions & 2 deletions src/components/AnswerForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState } from "react";
import styled from "styled-components";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import axiosInstance from "../api/AxiosInstance"; // Axios 인스턴스 가져오기

interface AnswerFormProps {
opinionId: number;
Expand All @@ -11,14 +11,17 @@ const AnswerForm = ({ opinionId }: AnswerFormProps) => {
const [content, setContent] = useState("");
const [charCount, setCharCount] = useState(0);
const queryClient = useQueryClient();
const token = localStorage.getItem("token");
console.log(token);

const mutation = useMutation({
mutationFn: (newComment: { content: string }) =>
axios.post(`/opinion/${opinionId}/comment`, newComment),
axiosInstance.post(`/opinion/${opinionId}/comment`, newComment),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["opinionDetails", opinionId],
});
window.location.reload();
},
});

Expand Down
15 changes: 8 additions & 7 deletions src/components/Boards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,14 @@ const Boards = () => {
/>
</div>
<GridContainer>
{data.results.content.map((article: any) => (
<PostItemMain
key={article.postId}
{...article}
postCategory={CATEGORY_LABELS[article.postCategory as Category]}
/>
))}
{data &&
data.results.content.map((article: any) => (
<PostItemMain
key={article.postId}
{...article}
postCategory={CATEGORY_LABELS[article.postCategory as Category]}
/>
))}
</GridContainer>
<Pagination
currentPage={page}
Expand Down
60 changes: 60 additions & 0 deletions src/components/TicleWarehouse.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import React, { useState } from "react";
import { useEffect } from "react";
import { useArticles } from "../hooks/useArticles";
import PostItemMain from "./PostItemMain";
import CategorySelector from "./CategorySelector";
import Pagination from "./Pagination";
import Select from "./Select";
import { Category, OrderBy, CATEGORY_LABELS } from "../types/ArticleBoards";
import { Container, GridContainer } from "../styles/ArticleBoards";
import { Option } from "../types/ArticleBoards";

const orderByOptions: Option[] = [
{ value: "LATEST", label: "최신순" },
{ value: "OLDEST", label: "오래된순" },
{ value: "SCRAPPED", label: "스크랩순" },
];

const Boards = () => {
const [page, setPage] = useState(1);
const [category, setCategory] = useState<Category | undefined>(undefined);
const [orderBy, setOrderBy] = useState<OrderBy>("LATEST");

const { data, isLoading, isError } = useArticles(page, category, orderBy);

useEffect(() => {
window.scrollTo(0, 0); // 페이지가 변경될 때마다 화면을 상단으로 스크롤합니다.
}, [page]);

if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error loading articles</div>;
console.log(data);
return (
<Container>
<div>
<Select
value={orderBy}
onChange={(e) => setOrderBy(e.target.value as OrderBy)}
options={orderByOptions}
/>
</div>
<GridContainer>
{data &&
data.results.content.map((article: any) => (
<PostItemMain
key={article.postId}
{...article}
postCategory={CATEGORY_LABELS[article.postCategory as Category]}
/>
))}
</GridContainer>
<Pagination
currentPage={page}
totalPages={data.results.totalPages}
onPageChange={setPage}
/>
</Container>
);
};

export default Boards;
Empty file removed src/hooks/useLogin.ts
Empty file.
11 changes: 9 additions & 2 deletions src/hooks/useOpinionDetail.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import axiosInstance from "../api/AxiosInstance";

interface Comment {
commentId: number;
Expand All @@ -9,17 +10,23 @@ interface Comment {
isHeart: boolean;
}

interface Result {
question: string;
userNickname: string;
responseList: Comment[];
}

interface OpinionDetails {
isSuccess: boolean;
code: string;
message: string;
results: Comment[];
results: Result;
}

const fetchOpinionDetails = async (
opinionId: number
): Promise<OpinionDetails> => {
const { data } = await axios.get(`/opinion/${opinionId}`);
const { data } = await axiosInstance.get(`/opinion/${opinionId}`);
return data;
};

Expand Down
32 changes: 19 additions & 13 deletions src/hooks/useSignup.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import { useMutation, UseMutationResult } from "@tanstack/react-query";
import axios, { AxiosError } from "axios";
import { SignupResponse, SignupErrorResponse, SignupPayload } from "../types/SignupTypes";
import { AxiosError } from "axios";
import {
SignupResponse,
SignupErrorResponse,
SignupPayload,
} from "../types/SignupTypes";
import axiosInstance from "../api/AxiosInstance";

// 회원가입 요청 함수
const signup = async (payload: SignupPayload): Promise<SignupResponse> => {
const { data } = await axios.post<SignupResponse>("/users/sign-up", {
const { data } = await axiosInstance.post<SignupResponse>("/users/sign-up", {
...payload,
category: "AI",
agreeTerms: true,
roles: ["user"],
});
return data;
};

const useSignup = (): UseMutationResult<SignupResponse, AxiosError<SignupErrorResponse>, SignupPayload> => {
// 회원가입 훅
const useSignup = (): UseMutationResult<
SignupResponse,
AxiosError<SignupErrorResponse>,
SignupPayload
> => {
return useMutation<SignupResponse, AxiosError<SignupErrorResponse>, SignupPayload>({
mutationFn: signup,
onSuccess: (data) => {
console.log("회원가입 성공!");
localStorage.setItem("token", data.token);
},
// onError: (error) => {
// console.error(
// error.response?.data?.message || "회원가입에 실패했습니다."
// );
// },
onError(error, variables, context) {
console.log(error);
onError: (error) => {
console.error(
error.response?.data?.message || "회원가입에 실패했습니다."
);
},
});
};
Expand Down
6 changes: 3 additions & 3 deletions src/pages/AnswerList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface Opinion {
const AnswerList = () => {
const { opinionId } = useParams<{ opinionId: string }>();
const { data, isLoading, isError } = useOpinionDetail(Number(opinionId));
const myNickname = "user5"; // replace with actual user nickname
const myNickname = data?.results.userNickname; // replace with actual user nickname
console.log(data);

if (isLoading) {
Expand All @@ -30,10 +30,10 @@ const AnswerList = () => {
return <div>Error loading opinion details</div>;
}

const myAnswers = data?.results.filter(
const myAnswers = data?.results.responseList.filter(
(opinion: Opinion) => opinion.nickname === myNickname
);
const otherAnswers = data?.results.filter(
const otherAnswers = data?.results.responseList.filter(
(opinion: Opinion) => opinion.nickname !== myNickname
);

Expand Down
39 changes: 12 additions & 27 deletions src/pages/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, { useState } from "react";
import { Link } from "react-router-dom";
import logo from "../assets/logo.png";
import styled from "styled-components";
import axiosInstance from "../api/AxiosInstance";
import {
Container,
LeftContainer,
Expand All @@ -14,6 +13,7 @@ import {
SearchInput,
Profile,
ProfileImg,
Button,
DropdownMenu,
DropdownItem,
DropdownLink,
Expand All @@ -24,40 +24,25 @@ import {
} from "../styles/Header";
import profileImg from "../assets/headerprofile.png";

const Button = styled(Link)`
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
height: 55px;
width: 143px;
background-color: #463efb;
border-radius: 10px;
border: none;
color: white;
font-weight: 600;
white-space: nowrap;
text-decoration: none;
`;


const Header: React.FC = () => {
// 로그인 상태 관리
const [isLoggedIn, setIsLoggedIn] = useState(true);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);

const toggleDropdown = () => {
setIsDropdownOpen(!isDropdownOpen);
};

const handleLogout = () => {
setIsLoggedIn(false);
// 로그아웃 로직 추가
const handleLogout = async () => {
try {
await axiosInstance.delete("/users/logout");
setIsLoggedIn(false);
setIsLoggedIn(false);
console.log("로그아웃 성공");
} catch (error) {
console.error("로그아웃 중 오류 발생:", error);
}
};

// 추후 useAuth로 인증 상태 가져오기
// const { isLoggedIn } = useAuth();

return (
<Container>
<LeftContainer>
Expand Down
11 changes: 8 additions & 3 deletions src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
SignupText,
} from "../styles/Login";
import { Errors, Touched } from "../types/LoginTypes";
import axiosInstance from "../api/AxiosInstance";

export const Login: React.FC = () => {
const [email, setEmail] = useState<string>("");
Expand Down Expand Up @@ -71,16 +72,20 @@ export const Login: React.FC = () => {

if (!errors.email && !errors.password) {
try {
const response = await axios.post("/users/sign-in", {
console.log("로그인 요청", { email, password });
const response = await axiosInstance.post("/users/sign-in", {
email,
password,
});

console.log("로그인 성공", response.data);

const token = response.data.token;
const token = response.data.results.accessToken;
localStorage.setItem("token", token);
navigate("/")
console.log(token);
console.log(localStorage.getItem("token"));

navigate("/");
} catch (error) {
if (axios.isAxiosError(error)) {
console.error("로그인 실패", error.response?.data || error.message);
Expand Down
Loading
Loading