Skip to content

Commit

Permalink
feat: 로그인 시도 시 틀릴 경우 경고 메세지 뜨도록 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
O-daeun committed May 19, 2024
1 parent 82ec8a0 commit fa09219
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 23 deletions.
4 changes: 2 additions & 2 deletions apis/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ export async function postSignUp(id: string, pw: string) {
}

export async function postSignIn(id: string, pw: string) {
const response = await axios.post(`${BASIC_URL}/sign-up`, {
const response = await axios.post(`${BASIC_URL}/sign-in`, {
email: id,
password: pw,
});
if (response.status < 200 || response.status >= 300) {
throw new Error('회원가입에 실패했습니다.');
throw new Error('로그인에 실패했습니다.');
}
const result = response.data.data;
return result;
Expand Down
1 change: 1 addition & 0 deletions contexts/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export function UserProvider({ children }: Props) {
const handleLoadUser = async () => {
const nextUser = await getUser();
setUser(nextUser);
console.log(user);
};

useEffect(() => {
Expand Down
36 changes: 36 additions & 0 deletions hooks/useAsync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useCallback, useState } from 'react';

type AsyncFunction<TArgs extends any[], TResult> = (
...args: TArgs
) => Promise<TResult>;

interface UseAsyncResult<TResult> {
pending: boolean;
error: Error | null;
requestFunction: (...args: any[]) => Promise<TResult | undefined>;
}

export default function useAsync<TArgs extends any[], TResult>(
asyncFunction: AsyncFunction<TArgs, TResult>
): UseAsyncResult<TResult> {
const [pending, setPending] = useState(false);
const [error, setError] = useState<Error | null>(null);

const requestFunction = useCallback(
async (...args: TArgs): Promise<TResult | undefined> => {
try {
setError(null);
setPending(true);
return await asyncFunction(...args);
} catch (error) {
setError(error as Error);
return;
} finally {
setPending(false);
}
},
[asyncFunction]
);

return { pending, error, requestFunction };
}
16 changes: 5 additions & 11 deletions pages/shared/[folderId].tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,32 @@
import React, { useCallback, useEffect, useState } from 'react';
import React, { useCallback, useContext, useEffect, useState } from 'react';
import Search from '../../components/Search/Search';
import { getFolders, getLinks, getUser } from '../../apis/api';
import { Layout, SectionWrap, TopWrap } from '../../styles/CommonPage.styled';
import * as S from '../../styles/SharedPage.styled';
import Profile from '../../components/Profile/Profile';
import CardList from '../../components/CardList/CardList';
import { useRouter } from 'next/router';
import { UserContext } from '@/contexts/UserContext';

export default function SharedPage() {
const { user } = useContext(UserContext);
const [links, setLinks] = useState([]);
const [folderName, setFolderName] = useState();
const [user, setUser] = useState({
id: 0,
created_at: '',
name: '',
image_source: '',
email: '',
auth_id: '',
});

interface ParamsType {
folderId: number;
}

console.log(user);

const router = useRouter();
const { folderId } = router.query as unknown as ParamsType;

const handleLoad = useCallback(async () => {
const nextLinks = await getLinks(folderId || 0);
const { name: nextFolderName } = await getFolders(folderId);
const nextUser = await getUser();
setLinks(nextLinks);
setFolderName(nextFolderName);
setUser(nextUser);
}, [folderId]);

useEffect(() => {
Expand Down
32 changes: 28 additions & 4 deletions pages/signin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,27 @@ import GoggleIcon from '../../src/images/login_google.svg';
import KakaotalkIcon from '../../src/images/login_kakaotalk.svg';
import EyeOnIcon from '../../src/images/eye_on.svg';
import EyeOffIcon from '../../src/images/eye_off.svg';
import { ChangeEvent, FormEvent, useState } from 'react';
import { ChangeEvent, FormEvent, useEffect, useState } from 'react';
import { postSignIn } from '@/apis/api';
import { useRouter } from 'next/router';
import { validateEmail, validateSignInPassword } from '@/utils/validate';
import useAsync from '@/hooks/useAsync';

export default function SignInPage() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showError, setShowError] = useState({
error: false,
email: { error: false, message: '' },
password: { error: false, message: '' },
passwordConform: { error: false, message: '' },
});
const [isVisiblePassword, setIsVisiblePassword] = useState(false);
const router = useRouter();
const {
pending: signInPending,
error: signInError,
requestFunction: signInRequest,
} = useAsync(postSignIn);

const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
Expand All @@ -35,10 +40,29 @@ export default function SignInPage() {
e.preventDefault();
validateEmail(email, setShowError);
validateSignInPassword(password, setShowError);
if (!showError.error) {
if (
(showError.email.error &&
showError.email.message !== '이메일을 확인해 주세요.') ||
(showError.password.error &&
showError.password.message !== '비밀번호를 확인해 주세요.')
)
return;
const result = await signInRequest(email, password);
if (signInError) {
setShowError((prev) => ({
...prev,
email: {
error: true,
message: '이메일을 확인해 주세요.',
},
password: {
error: true,
message: '비밀번호를 확인해 주세요.',
},
}));
return;
}
const result = await postSignIn(email, password);
if (!result) return;
localStorage.setItem('accessToken', result?.accessToken);
router.push('/folder');
};
Expand Down
7 changes: 5 additions & 2 deletions pages/signup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export default function SignUpPage() {
const [password, setPassword] = useState('');
const [passwordConform, setPasswordConform] = useState('');
const [showError, setShowError] = useState({
error: false,
email: { error: false, message: '' },
password: { error: false, message: '' },
passwordConform: { error: false, message: '' },
Expand All @@ -47,7 +46,11 @@ export default function SignUpPage() {
validateEmail(email, setShowError);
validateSignUpPassword(password, setShowError);
validatePasswordConform(passwordConform, password, setShowError);
if (showError.error) {
if (
showError.email.error ||
showError.password.error ||
showError.passwordConform.error
) {
return;
}
const result = await postSignUp(email, password);
Expand Down
4 changes: 0 additions & 4 deletions utils/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export function validateEmail(
email: string,
setter: Dispatch<
SetStateAction<{
error: boolean;
email: { error: boolean; message: string };
password: { error: boolean; message: string };
passwordConform: { error: boolean; message: string };
Expand Down Expand Up @@ -37,7 +36,6 @@ export function validateSignUpPassword(
password: string,
setter: Dispatch<
SetStateAction<{
error: boolean;
email: { error: boolean; message: string };
password: { error: boolean; message: string };
passwordConform: { error: boolean; message: string };
Expand Down Expand Up @@ -65,7 +63,6 @@ export function validateSignInPassword(
password: string,
setter: Dispatch<
SetStateAction<{
error: boolean;
email: { error: boolean; message: string };
password: { error: boolean; message: string };
passwordConform: { error: boolean; message: string };
Expand All @@ -90,7 +87,6 @@ export function validatePasswordConform(
password: string,
setter: Dispatch<
SetStateAction<{
error: boolean;
email: { error: boolean; message: string };
password: { error: boolean; message: string };
passwordConform: { error: boolean; message: string };
Expand Down

0 comments on commit fa09219

Please sign in to comment.