Skip to content

Commit

Permalink
Merge pull request #86 from JangGusWjd/update/api
Browse files Browse the repository at this point in the history
[FE-UPDATE] 분리된 학과 게시판 API 연결
  • Loading branch information
JangGusWjd authored Jun 17, 2024
2 parents 481c870 + f8f9a89 commit 275a920
Show file tree
Hide file tree
Showing 30 changed files with 312 additions and 147 deletions.
34 changes: 33 additions & 1 deletion src/api/fetchData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ const API_BASE_URL = "http://3.35.123.253/api";
export const fetchData = async (endpoint: string) => {
const storedAuth = localStorage.getItem("auth");
const auth = storedAuth ? JSON.parse(storedAuth) : null;
const majorId = auth ? auth.major_id : null;
let majorId = auth ? auth.major_id : null;

if (!majorId) {
const selectedMajorId = localStorage.getItem("selected_major_id");
majorId = selectedMajorId ? parseInt(selectedMajorId) : null;
}

try {
const response = await axios.get(`${API_BASE_URL}/${majorId}${endpoint}`);
return response.data;
Expand All @@ -14,6 +20,32 @@ export const fetchData = async (endpoint: string) => {
}
};

export const fetchNoMajorData = async (endpoint: string) => {
try {
const response = await axios.get(`${API_BASE_URL}${endpoint}`);
return response.data;
} catch (error) {
console.log(error);
}
};

export const fetchNoMajorTokenData = async (endpoint: string) => {
const storedAuth = localStorage.getItem("auth");
const auth = storedAuth ? JSON.parse(storedAuth) : null;
const accessToken = auth ? auth.access_token : null;

try {
const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
console.log(error);
}
};

export const fetchTokenData = async (endpoint: string) => {
const storedAuth = localStorage.getItem("auth");
const auth = storedAuth ? JSON.parse(storedAuth) : null;
Expand Down
9 changes: 5 additions & 4 deletions src/api/postData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ const API_BASE_URL = "http://3.35.123.253/api";
export const postData = async (endpoint: string, data: any) => {
try {
const response = await axios.post(`${API_BASE_URL}${endpoint}`, data);
console.log("서버로부터의 응답:", response.data);
// console.log("서버로부터의 응답:", response.data);
return response.data;
} catch (error) {
console.log(error);
console.log(data);
} catch (error: any) {
// console.log(error);
// console.log(data);
return error;
}
};

Expand Down
3 changes: 3 additions & 0 deletions src/assets/icon/nobook.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 15 additions & 9 deletions src/components/community/CommunityMain.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ const CommunityMain = () => {
endpoint = `/boards/posts/search/?keyword=${searchKeyword}`;
}
const data = await fetchData(endpoint);
if (data) {
setCommunityData(data.sort((a: any, b: any) => b.id - a.id));
// if (data) {
// setCommunityData(data.sort((a: any, b: any) => b.id - a.id));
// }
if (Array.isArray(data)) {
setCommunityData(data.sort((a, b) => b.id - a.id));
}
};

Expand All @@ -42,7 +45,8 @@ const CommunityMain = () => {
setSearchKeyword(event.target.value);
};

const handleSearchClick = () => {
const handleSearchClick = (event: React.FormEvent) => {
event.preventDefault();
setIsSearching(true);
};

Expand All @@ -56,15 +60,17 @@ const CommunityMain = () => {

return (
<div className="community-container">
<div className="search">
<form className="search" onSubmit={handleSearchClick}>
<input
type="text"
placeholder="검색어를 입력해주세요"
value={searchKeyword}
onChange={handleSearchInputChange}
/>
<SearchIcon onClick={handleSearchClick} />
</div>
<button type="submit" onSubmit={handleSearchClick}>
<SearchIcon onClick={handleSearchClick} />
</button>
</form>
<div className="community-filtering">
<ul>
<li
Expand Down Expand Up @@ -98,10 +104,10 @@ const CommunityMain = () => {
대외활동
</li>
<li
onClick={() => setSelectedCategory("우리학교는")}
className={selectedCategory === "우리학교는" ? "selected" : ""}
onClick={() => setSelectedCategory("학교이야기")}
className={selectedCategory === "학교이야기" ? "selected" : ""}
>
우리학교는
학교이야기
</li>
</ul>
<button onClick={handleWriteClick}>
Expand Down
2 changes: 1 addition & 1 deletion src/components/community/CommunityWrite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const CommunityWrite = () => {
<option value="잡담/수다">잡담/수다</option>
<option value="인턴리뷰">인턴리뷰</option>
<option value="대외활동">대외활동</option>
<option value="우리학교는">우리학교는</option>
<option value="우리학교는">학교이야기</option>
</select>
</div>
<div>
Expand Down
41 changes: 26 additions & 15 deletions src/components/home/HomeLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useAuth } from "../../hooks/useAuth";
const HomeLogin = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const navigate = useNavigate();
const { login } = useAuth();

Expand All @@ -26,23 +27,32 @@ const HomeLogin = () => {
password,
};

const response = await postData("/login/", loginData);
try {
const response = await postData("/login/", loginData);

if (response) {
const data = await response.token;
login(
data.access,
data.refresh,
data.user_name,
data.school_name,
data.major_name,
data.admission_date,
data.user_id,
data.major_id
if (response) {
const data = await response.token;
login(
data.access,
data.refresh,
data.user_name,
data.school_name,
data.major_name,
data.admission_date,
data.user_id,
data.major_id,
data.major_category_name
);
// alert("로그인에 성공하였습니다.");
navigate("/main");
window.location.reload();
} else {
throw new Error("Invalid response");
}
} catch (error) {
setErrorMessage(
"로그인에 실패했습니다. 아이디와 비밀번호를 확인해주세요."
);
alert("로그인에 성공하였습니다.");
navigate("/main");
window.location.reload();
}
};

Expand All @@ -69,6 +79,7 @@ const HomeLogin = () => {
value={password}
onChange={handleInputChange}
/>
{errorMessage && <p className="error-message">{errorMessage}</p>}
<input type="submit" value="로그인" onSubmit={handleLogin} />
</form>
<div className="login-bottom">
Expand Down
55 changes: 27 additions & 28 deletions src/components/home/HomeSearch.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
import "../../styles/home/HomeSearch.scss";
import { ReactComponent as SearchIcon } from "../../assets/icon/search.svg";
import "../../styles/home/HomeSearch.scss";
import { useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import { fetchNoMajorData } from "../../api/fetchData";
import { MajorData } from "../../types/Types";

const HomeSearch = () => {
const [majorData, setMajorData] = useState<MajorData[]>([]);
const navigate = useNavigate();
const goMain = () => {

useEffect(() => {
const fetchMajorData = async () => {
const data = await fetchNoMajorData("/majors/");
if (data) {
setMajorData(data);
}
};
fetchMajorData();
}, []);
const goMain = (majorId: number) => {
localStorage.setItem("selected_major_id", majorId.toString());
navigate("/main");
};
return (
Expand All @@ -14,32 +29,16 @@ const HomeSearch = () => {
<input type="text" placeholder="학과, 전공을 검색하세요." />
<SearchIcon />
</div>
<div className="home-major-list" onClick={goMain}>
<p>IT</p>
<span>
컴퓨터공학, 소프트웨어, 정보통신, 정보보호, IT융합, 멀티미디어
</span>
</div>
<div className="home-major-list" onClick={goMain}>
<p>경영경제</p>
<span>경영, 회계, 마케팅, 금융, 경제</span>
</div>
<div className="home-major-list" onClick={goMain}>
<p>인문사회과학</p>
<span>국어국문, 영어영문, 사회학, 심리학, 정치외교, 사학,</span>
</div>
<div className="home-major-list" onClick={goMain}>
<p>공과</p>
<span>전자공학, 기계공학, 화학공학, 건축공학, 신소재공학</span>
</div>
<div className="home-major-list" onClick={goMain}>
<p>자연과학</p>
<span>물리학, 화학, 생물학, 지구과학, 수학, 통계학</span>
</div>
<div className="home-major-list" onClick={goMain}>
<p>예술대학</p>
<span>미술, 패션디자인, 음악, 연극영화, 무용</span>
</div>
{majorData.map((item, index) => (
<div
key={index}
className="home-major-list"
onClick={() => goMain(item.id)}
>
<p>{item.major_category_name}</p>
<span>{item.major}</span>
</div>
))}
</div>
);
};
Expand Down
41 changes: 26 additions & 15 deletions src/components/login/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useAuth } from "../../hooks/useAuth";
const LoginForm = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const navigate = useNavigate();
const { login } = useAuth();

Expand All @@ -27,23 +28,32 @@ const LoginForm = () => {
password,
};

const response = await postData("/login/", loginData);
try {
const response = await postData("/login/", loginData);

if (response) {
const data = await response.token;
login(
data.access,
data.refresh,
data.user_name,
data.school_name,
data.major_name,
data.admission_date,
data.user_id,
data.major_id
if (response && response.token) {
const data = response.token;
login(
data.access,
data.refresh,
data.user_name,
data.school_name,
data.major_name,
data.admission_date,
data.user_id,
data.major_id,
data.major_category_name
);
// alert("로그인에 성공하였습니다.");
navigate("/main");
window.location.reload();
} else {
throw new Error("Invalid response");
}
} catch (error) {
setErrorMessage(
"로그인에 실패했습니다. 아이디와 비밀번호를 확인해주세요."
);
alert("로그인에 성공하였습니다.");
navigate("/main");
window.location.reload();
}
};

Expand Down Expand Up @@ -79,6 +89,7 @@ const LoginForm = () => {
<input type="radio" id="login-keep" />
<label htmlFor="login-keep">로그인 상태 유지</label>
</div>
{errorMessage && <p className="error-message">{errorMessage}</p>}
<input type="submit" value="로그인" onSubmit={handleLogin} />
</form>
<div className="login-bottom">
Expand Down
4 changes: 2 additions & 2 deletions src/components/mypage/MyInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ReactComponent as SchoolIcon } from "../../assets/icon/school.svg";
import { ReactComponent as EmailIcon } from "../../assets/icon/email.svg";
import "../../styles/mypage/MyInfo.scss";
import { useState, useEffect } from "react";
import { fetchTokenData } from "../../api/fetchData";
import { fetchNoMajorTokenData } from "../../api/fetchData";
import { UserInfo } from "../../types/Types";

const MyInfo = () => {
Expand All @@ -16,7 +16,7 @@ const MyInfo = () => {
const storedAuth = localStorage.getItem("auth");
const auth = storedAuth ? JSON.parse(storedAuth) : null;
const userId = auth ? auth.user_id : null;
const data = await fetchTokenData(`/profile/users/${userId}/`);
const data = await fetchNoMajorTokenData(`/profile/users/${userId}/`);
if (data) {
setUserData(data);
}
Expand Down
8 changes: 4 additions & 4 deletions src/components/mypage/MyPost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import "../../styles/mypage/MyPost.scss";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { StudyData, CommunityData } from "../../types/Types";
import { fetchTokenData } from "../../api/fetchData";
import { fetchNoMajorTokenData } from "../../api/fetchData";

const MyPost = () => {
const [selectedSection, setSelectedSection] = useState("study");
Expand All @@ -15,7 +15,7 @@ const MyPost = () => {
const navigate = useNavigate();

const fetchData = async (endpoint: string) => {
const response = await fetchTokenData(endpoint);
const response = await fetchNoMajorTokenData(endpoint);
const data = response ? response.sort((a: any, b: any) => b.id - a.id) : [];
return data;
};
Expand Down Expand Up @@ -43,11 +43,11 @@ const MyPost = () => {
};

const handleStudyItemClick = (studyId: number) => {
navigate(`/study/${studyId}`);
navigate(`/main/study/${studyId}`);
};

const handleCommunityItemClick = (contentId: number) => {
navigate(`/community/${contentId}`);
navigate(`/main/community/${contentId}`);
};

return (
Expand Down
Loading

0 comments on commit 275a920

Please sign in to comment.