기본세팅
Reducer
상태관리 하는 법 변수 한 곳에서 관리
store > configureStore.ts
import { legacy_createStore as createStore } from 'redux';
import rootReducer from './reducers';
const configureStore = (): any => createStore(rootReducer);
export default configureStore;
store > reducers.ts
import { combineReducers } from 'redux';
import main from '../redux/reducers/mainReducer';
import app from '../redux/reducers/appReducer';
import login from '../redux/reducers/loginReducer';
const rootReducer = combineReducers({
main,
app,
login,
});
export default rootReducer;
export type RootState = ReturnType<typeof rootReducer>;
index.tsx
import configureStore from './store/configureStore';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement,
);
const store = configureStore();
root.render(
<Provider store={store}>
<App />
</Provider>,
);
로그인 상태관리 예시
redux > actions > loginActions.ts
export type LoginAction = {
type: typeof ActionTypes.SET_AUTOLOGIN_STATUS;
payload: {
loginStatus: E_INTRO_LOGIN_STATE;
};
};
redux > constatns > loginConstatns.ts
enum ActionTypes {
SET_AUTOLOGIN_STATUS = 'login/SET_AUTOLOGIN_STATUS',
}
export default ActionTypes;
utils > enum.ts
/**
* @name 로그인 결과 상태 값
* @param NONE 자동로그인 미설정
* @param SUCCESS 로그인 성공
* @param FAIL 로그인 실패
* @param INIT 로그인 처리 전 or 로그아웃
*/
export enum E_INTRO_LOGIN_STATE {
'NONE' = 'NONE',
'SUCCESS' = 'SUCCESS',
'FAIL' = 'FAIL',
'INIT' = '',
}
로그아웃 예시
import { useDispatch } from 'react-redux';
import { actionSetLoginStatus } from 'src/redux/actions/loginActions';
type Props = {
loginId: string;
};
function SettingDefaultLogout(props: Props): React.ReactElement {
const dispatch = useDispatch();
const apiUserLogoutMutation = useMutation(apiUserLogout, {
onSuccess: () => {
//로그인 상태 및 웰컴팝업 노출설정 초기화
dispatch(actionSetLoginStatus(E_INTRO_LOGIN_STATE.INIT));
dispatch(actionInitWelcomePopup());
//멤버스 로그아웃 처리 (스토리지 삭제 및 JSP 호출)
moveSsoCallLogout();
},
onError: () => {
dispatch(actionCloseLoadingPopup());
alert('로그아웃에 실패하였습니다. 잠시후 다시 시도해주세요.');
},
});
const handleClickLogout = () => {
gaEvent('로그아웃 버튼', '', '');
dispatch(actionOpenLoadingPopup());
apiUserLogoutMutation.mutate();
};
useEffect(() => {
return () => {
dispatch(actionCloseLoadingPopup());
};
}, [dispatch]);
return (
<li>
<div className="title">
<h4>{props.loginId}</h4>
<div className="right">
<button className="text-btn" onClick={handleClickLogout}>
로그아웃
</button>
</div>
</div>
</li>
);
}
export default SettingDefaultLogout;
'Framework > React' 카테고리의 다른 글
[React] Code Splitting & lazy (0) | 2024.12.04 |
---|---|
[React] Redux - payload 적용 (0) | 2024.12.03 |
Redux란 (0) | 2024.11.26 |
e.preventDefault()와 e.stopPropagation() (0) | 2024.11.22 |
setTimeout(function, 0) (0) | 2024.11.21 |