Skip to content

Commit

Permalink
feat(login): useLogin 을 State Reducer Pattern 을 활용하도록 구조 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
innocarpe committed Oct 5, 2023
1 parent d1261dc commit ea1387e
Showing 1 changed file with 42 additions and 10 deletions.
52 changes: 42 additions & 10 deletions apps/react-world/src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,73 @@
import { useState } from 'react';
import { useReducer } from 'react';
import type { LoginUserErrors } from '@/apis/login/LoginService.types'; // 로그인 관련 타입으로 수정
import LoginService from '@/apis/login/LoginService'; // LoginService로 수정
import { saveTokenToCookie } from '@/utils/jwtUtils';
import type { UserCredentials } from '@/app-types/UserCredentials';

export type LoginStatus = 'idle' | 'loggingIn' | 'success' | 'failed';

type LoginState = {
loginError: LoginUserErrors | null;
loginStatus: LoginStatus;
};

type LoginAction =
| { type: 'LOGIN_START' }
| { type: 'LOGIN_SUCCESS'; token: string }
| { type: 'LOGIN_ERROR'; error: LoginUserErrors }
| { type: 'LOGIN_FAILED' };

const loginReducer = (state: LoginState, action: LoginAction): LoginState => {
switch (action.type) {
case 'LOGIN_START':
return { ...state, loginStatus: 'loggingIn', loginError: null };
case 'LOGIN_SUCCESS':
return { ...state, loginStatus: 'success', loginError: null };
case 'LOGIN_ERROR':
return { ...state, loginStatus: 'failed', loginError: action.error };
case 'LOGIN_FAILED':
return { ...state, loginStatus: 'failed' };
default:
return state;
}
};

const useLogin = () => {
const [loginError, setLoginError] = useState<LoginUserErrors | null>(null);
const [loginStatus, setLoginStatus] = useState<LoginStatus>('idle');
const [state, dispatch] = useReducer(loginReducer, {
loginError: null,
loginStatus: 'idle',
});

const handleLogin = async (data: UserCredentials) => {
dispatch({ type: 'LOGIN_START' });

try {
setLoginStatus('loggingIn');
const response = await LoginService.loginUser(data);
// JWT 토큰을 쿠키에 저장
if (response && response.user && response.user.token) {
saveTokenToCookie(response.user.token);
dispatch({ type: 'LOGIN_SUCCESS', token: response.user.token });
console.log('login suceess');
}
setLoginStatus('success');
console.log('login suceess');
return response;
} catch (error) {
if (error && typeof error === 'object' && 'errors' in error) {
setLoginError(error.errors as LoginUserErrors);
dispatch({
type: 'LOGIN_ERROR',
error: error.errors as LoginUserErrors,
});
console.error('LoginUserErrors: ', error.errors);
} else {
dispatch({ type: 'LOGIN_FAILED' });
console.error('An unexpected error occurred:', error);
}
setLoginStatus('failed');
return null;
}
};

return {
loginError,
loginStatus,
loginError: state.loginError,
loginStatus: state.loginStatus,
handleLogin,
};
};
Expand Down

0 comments on commit ea1387e

Please sign in to comment.