Skip to content

Commit

Permalink
hotfix : 회원가입,검색문자열,프로필사진, 비정상 url,갱신 데이터 ui 반영 등 (#38)
Browse files Browse the repository at this point in the history
* hotfix : 회원가입,검색문자열,프로필사진, 비정상 url,갱신 데이터 ui 반영 등

* fix : 별점 등록&수정 버그 코드 수정

* 회원가입 모달 에러 메시지 수정
  • Loading branch information
ohsuhyeon0119 authored Feb 5, 2024
1 parent a3129b0 commit 7c43eac
Show file tree
Hide file tree
Showing 13 changed files with 97 additions and 55 deletions.
1 change: 0 additions & 1 deletion src/apis/custom.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export function defaultResponseHandler(res: Response) {
if (!res.ok) {
console.log(res); //res.json().code=="token_not_valid"
/*res.json().then((data)=>{
console.log;
if(data.code=="token_not_valid"){
Expand Down
10 changes: 4 additions & 6 deletions src/components/Content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ function ContentPanel({
const { setCurrentModal: setLayoutCurrentModal } =
useOutletContext<OutletContextType>();

const [myRate, setMyRate] = useState(content.my_rate ?? null);

const { isLogined, accessToken } = useAuthContext();
const myState = content.my_state ?? null;

Expand Down Expand Up @@ -119,13 +117,13 @@ function ContentPanel({
<div className={styles.userRatingCon}>
<div className={styles.starRatingBox}>
<StarRating
myRate={myRate}
setMyRate={setMyRate}
refetchContent={refetchContent}
myRateData={content.my_rate}
movieCD={content.movieCD}
/>
</div>
<div className={styles.userRatingTextBox}>
{rateStr[myRate ? myRate.my_rate * 2 : 0]}
{rateStr[content.my_rate ? content.my_rate.my_rate * 2 : 0]}
</div>
</div>
<div className={styles.avgRatingCon}>
Expand Down Expand Up @@ -202,7 +200,7 @@ function ContentPanel({
</ul>
</nav>
<MyCommentBox
myRate={myRate ? myRate.my_rate : 0}
myRate={content.my_rate ? content.my_rate.my_rate : 0}
closeModal={() => {
setCurrentModal(null);
}}
Expand Down
21 changes: 14 additions & 7 deletions src/components/SignupModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export default function SignupModal({ setCurrentModal }: SignupModalProps) {
const { setAccessToken } = useAuthContext();
const error = {
name:
nameInput.length < 2 || nameInput.length > 20 || nameInput.includes(" ")
? "정확하지 않은 이름입니다."
nameInput.length < 3 || nameInput.length > 20
? "세 글자 이상 20글자 이하의 닉네임을 입력해주세요"
: "",
id:
idInput.length < 2 || idInput.length > 20 || idInput.includes(" ")
Expand All @@ -47,11 +47,13 @@ export default function SignupModal({ setCurrentModal }: SignupModalProps) {
})
.then((data) => {
if ("access" in data) {
alert("회원가입 성공!");
setIsSignupSuccess(true);
return;
}
if ("username" in data && data.username[0].includes("already exists")) {
setAuthErrorMessage("이미 존재하는 아이디입니다.");
} else if (
"username" in data &&
data.username[0].includes("already exists")
) {
return setAuthErrorMessage("이미 존재하는 아이디입니다.");
} else if (
"non_field_errors" in data &&
data.non_field_errors[0].includes("didn't match.")
Expand All @@ -62,6 +64,11 @@ export default function SignupModal({ setCurrentModal }: SignupModalProps) {
data.non_field_errors[0].includes("too similar")
) {
setAuthErrorMessage("아이디와 비밀번호가 매우 유사합니다.");
} else if (
"password1" in data &&
data.password1[0].includes("common")
) {
setAuthErrorMessage("너무 흔한 비밀번호입니다.");
} else {
setAuthErrorMessage("예상치 못한 오류가 발생하였습니다.");
}
Expand Down Expand Up @@ -291,7 +298,7 @@ export default function SignupModal({ setCurrentModal }: SignupModalProps) {
window.open(
"/auth/toKakao",
"_blank",
"width=350,height=600",
"width=350,height=600"
);
}}
>
Expand Down
29 changes: 12 additions & 17 deletions src/components/StarRating.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,20 @@ function Star(props: StarProps) {
}

type StarRatingProps = {
myRate: {
movieCD: string;
refetchContent: () => void;
myRateData: {
id: number;
my_rate: number;
} | null;
setMyRate: (
newRate: {
id: number;
my_rate: number;
} | null,
) => void;
movieCD: string;
};

export default function StarRating({
myRate,
setMyRate,
movieCD,
refetchContent,
myRateData,
}: StarRatingProps) {
const savedRating = myRate ? myRate.my_rate : 0;
const savedRating = myRateData ? myRateData.my_rate : 0;
const [selectedRating, setSelectedRating] = useState(savedRating);
const [hover, setHover] = useState(false);
const { isLogined, accessToken } = useAuthContext();
Expand All @@ -88,29 +83,29 @@ export default function StarRating({
if (!isLogined) {
setCurrentModal("login");
} else {
if (myRate) {
if (myRateData) {
if (rating === savedRating) {
deleteRatingRequest(myRate.id, accessToken ?? "")
deleteRatingRequest(myRateData.id, accessToken ?? "")
.then(() => {
setMyRate(null);
setSelectedRating(0);
refetchContent();
})
.catch((e) => console.log(e));
} else {
updateRatingRequest(myRate.id, rating, accessToken ?? "")
updateRatingRequest(myRateData.id, rating, accessToken ?? "")
.then(defaultResponseHandler)
.then((data) => {
setMyRate({ ...data, my_rate: data.rate });
setSelectedRating(data.rate);
refetchContent();
})
.catch((e) => console.log(e));
}
} else {
createRatingRequest(movieCD, rating, accessToken ?? "")
.then(defaultResponseHandler)
.then((data) => {
setMyRate({ ...data, my_rate: data.rate });
setSelectedRating(data.rate);
refetchContent();
})
.catch((e) => console.log(e));
}
Expand Down
7 changes: 3 additions & 4 deletions src/components/user/SettingModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export default function SettingModal({ setCurrentModal }: SettingModalProps) {

type ButtonBoxProps = {
setAlertMessage: (
alertMessage: "logoutAlert" | "withdrawalAlert" | "clipboard" | null,
alertMessage: "logoutAlert" | "withdrawalAlert" | "clipboard" | null
) => void;
};

Expand Down Expand Up @@ -166,9 +166,8 @@ function WithdrawalAlertBoxContainer({ setAlertMessage }: ButtonBoxProps) {
alert("회원탈퇴 성공");
window.location.href = "/";
})
.catch((e) => {
console.log(e);
alert("로그아웃 실패");
.catch(() => {
window.location.href = "/";
});
}}
>
Expand Down
22 changes: 15 additions & 7 deletions src/components/user/User.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// import { useEffect } from "react";
import { useAuthContext } from "../../contexts/authContext";
import styles from "./User.module.scss";
import { Link, useParams } from "react-router-dom";
import { Link, useNavigate, useParams } from "react-router-dom";
import { OutletContextType } from "../../pages/Layout";
import { useOutletContext } from "react-router-dom";
import { useEffect, useState } from "react";
Expand All @@ -23,8 +23,8 @@ export default function User() {
const pageMode = !loginUserId
? "notLoggedIn"
: pageUserId === loginUserId.toString()
? "myPage"
: "otherPage";
? "myPage"
: "otherPage";
// myPage : 팔로우 버튼 보여주지 않는다 / 좋아요 섹션 보여준다
// otherPage : 팔로우 버튼 보여준다(팔로우or언팔로우) / 좋아요 섹션 보여주지 않는다.
// isLoggedIn : 팔로우 버튼 보여준다(무조건 팔로우) / 좋아요 섹션 보여주지 않는다.
Expand All @@ -34,9 +34,11 @@ export default function User() {
const [isMyFollowing, setIsMyFollowing] = useState<boolean>(false);
const [isMyFollowingLoading, setIsMyFollowingLoading] = useState(true);
const loading = pageUserloading || isMyFollowingLoading;

const navigate = useNavigate();
const [refetch, setRefetch] = useState(false);
const refetchPageUser = () => setRefetch(!refetch);
const followButtonClickHandler = (
e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
e: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
e.preventDefault();
if (!pageUser) return;
Expand All @@ -46,11 +48,13 @@ export default function User() {
.then(defaultResponseHandler)
.then(() => {
setIsMyFollowing(false);
refetchPageUser();
})
: postAddFollow(accessToken, pageUser.id)
.then(defaultResponseHandler)
.then(() => {
setIsMyFollowing(true);
refetchPageUser();
});
};

Expand All @@ -63,14 +67,18 @@ export default function User() {
setTitle(
data.nickname
? `${data.nickname}님의 프로필 페이지 - 와플피디아`
: "와플피디아 - 영화 평가 서비스",
: "와플피디아 - 영화 평가 서비스"
);
setPageUser(data);
})
.catch(() => {
alert("잘못된 요청입니다.");
navigate(-1);
})
.finally(() => {
setPageUserLoading(false);
});
}, [pageUserId, myUserData]);
}, [pageUserId, myUserData, , refetch]);

// 유저데이터에 팔로잉 리스트가 없어서 추가로 가져와야 함

Expand Down
4 changes: 4 additions & 0 deletions src/components/user/UserEditModal.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,7 @@
}
}
}
.errorMessage {
color: red;
font-size: 12px;
}
20 changes: 17 additions & 3 deletions src/components/user/UserEditModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import profileDefault from "../../assets/user_default.jpg";
import useUserEdit from "../../hooks/useUserEdit";
import usePreventScroll from "../../hooks/usePreventScroll";
import useHandlePopState from "../../hooks/useHandlePopState";

import { useState } from "react";
type UserEditModalProps = {
setCurrentModal: (currentModal: CurrentModalType) => void;
};

export default function UserEditModal({ setCurrentModal }: UserEditModalProps) {
const [nicknameError, setNicknameError] = useState<null | string>(null);
const {
nickname,
bio,
Expand Down Expand Up @@ -59,7 +60,11 @@ export default function UserEditModal({ setCurrentModal }: UserEditModalProps) {
취소
</button>
<h2>프로필 변경</h2>
<button type="submit" className={styles.saveBtn}>
<button
type="submit"
disabled={!!nicknameError}
className={styles.saveBtn}
>
확인
</button>
</header>
Expand Down Expand Up @@ -95,8 +100,17 @@ export default function UserEditModal({ setCurrentModal }: UserEditModalProps) {
type="text"
id="nicknameEdit"
value={nickname}
onChange={handleNickname}
onChange={(e) => {
if (e.target.value.replace(/\s/g, "").length) {
setNicknameError(null);
} else {
setNicknameError("공백을 제외한 한글자 이상을 입력해주세요.");
}

handleNickname(e);
}}
/>
<p className={styles.errorMessage}>{nicknameError}</p>
</div>
<div className={styles.textInputCon}>
<label htmlFor="bioEdit">소개</label>
Expand Down
14 changes: 11 additions & 3 deletions src/hooks/useUserEdit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ export default function useUserEdit() {
const [nickname, setNickname] = useState(myUserData?.nickname ?? "");
const [bio, setBio] = useState(myUserData?.bio ?? "");
const [backgroundPhotoFile, setBackgroundPhotoFile] = useState<File | null>(
null,
null
);
const [profilePhotoFile, setProfilePhotoFile] = useState<File | null>(null);
const [backgroundPhotoUrl, setBackgroundPhotoUrl] = useState(
myUserData?.background_photo ?? "",
myUserData?.background_photo ?? ""
);
const [profilePhotoUrl, setProfilePhotoUrl] = useState(
myUserData?.profile_photo ?? "",
myUserData?.profile_photo ?? ""
);

const handleBackgroundPhoto = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
const reader = new FileReader();

if (!file) return;
if (file["type"].split("/")[0] !== "image")
return alert("이미지 파일만 업로드 가능합니다.");

reader.onload = (e) => {
const previewPhotoUrl = e.target?.result as string | null | undefined;
setBackgroundPhotoFile(file ?? null);
Expand All @@ -34,6 +38,10 @@ export default function useUserEdit() {
const file = e.target.files?.[0];
const reader = new FileReader();

if (!file) return;
if (file["type"].split("/")[0] !== "image")
return alert("이미지 파일만 업로드 가능합니다.");

reader.onload = (e) => {
const previewPhotoUrl = e.target?.result as string | null | undefined;
setProfilePhotoFile(file ?? null);
Expand Down
7 changes: 6 additions & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { AuthContextProvider } from "./contexts/authContext.tsx";
import UserStorageSubPage from "./pages/user/UserStorageSubPage.tsx";
import UserFollowerPage from "./pages/user/UserFollowerPage.tsx";
import AuthToKaKao from "./pages/AuthToKakao.tsx";
import { Navigate } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
Expand Down Expand Up @@ -81,6 +82,10 @@ const router = createBrowserRouter([
path: "/search",
element: <SearchPage />,
},
{
path: "/*",
element: <Navigate to={"/"} replace={true}></Navigate>,
},
],
},
{ path: "/auth/callback/kakao", element: <AuthCallBackKakaoPage /> },
Expand All @@ -90,5 +95,5 @@ const router = createBrowserRouter([
ReactDOM.createRoot(document.getElementById("root")!).render(
<AuthContextProvider>
<RouterProvider router={router} />
</AuthContextProvider>,
</AuthContextProvider>
);
Loading

0 comments on commit 7c43eac

Please sign in to comment.