Replies: 1 comment
-
|
MVI 패턴으로 변형 // Model (State + Reducer)
const initialState = {
email: "",
password: "",
error: "",
message: ""
};
function loginReducer(state, action) {
switch (action.type) {
case "CHANGE_EMAIL":
return { ...state, email: action.payload };
case "CHANGE_PASSWORD":
return { ...state, password: action.payload };
case "LOGIN_SUCCESS":
return { ...state, error: "", message: "로그인 성공!" };
case "LOGIN_ERROR":
return { ...state, message: "", error: action.payload };
default:
return state;
}
}
// Service (로그인 검증)
const AuthService = {
login({ email, password }) {
if (!email.includes("@")) throw new Error("이메일 형식이 올바르지 않습니다");
if (password.length < 6) throw new Error("비밀번호는 최소 6자 이상이어야 합니다");
return { success: true, token: "abc123" };
}
};
// Intent (유저 이벤트 → dispatch)
function useLoginIntent(dispatch, state) {
const onChangeEmail = (e) => dispatch({ type: "CHANGE_EMAIL", payload: e.target.value });
const onChangePassword = (e) => dispatch({ type: "CHANGE_PASSWORD", payload: e.target.value });
const onLogin = () => {
try {
AuthService.login({ email: state.email, password: state.password });
dispatch({ type: "LOGIN_SUCCESS" });
} catch (err) {
dispatch({ type: "LOGIN_ERROR", payload: err.message });
}
};
return { onChangeEmail, onChangePassword, onLogin };
}
// View (UI만 담당)
function LoginView() {
const [state, dispatch] = React.useReducer(loginReducer, initialState);
const { onChangeEmail, onChangePassword, onLogin } = useLoginIntent(dispatch, state);
return (
<div style={{ maxWidth: 300, margin: "50px auto", fontFamily: "sans-serif" }}>
<h2>로그인 (MVI)</h2>
<input
placeholder="Email"
value={state.email}
onChange={onChangeEmail}
style={{ display: "block", marginBottom: 10, width: "100%" }}
/>
<input
placeholder="Password"
type="password"
value={state.password}
onChange={onChangePassword}
style={{ display: "block", marginBottom: 10, width: "100%" }}
/>
<button onClick={onLogin} style={{ width: "100%", padding: 8 }}>
로그인
</button>
{state.error && <p style={{ color: "red", marginTop: 10 }}>{state.error}</p>}
{state.message && <p style={{ color: "green", marginTop: 10 }}>{state.message}</p>}
</div>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
MVC 패턴을 적용된 코드를 다른 패턴으로 적용해보기
구현이 필요한 요구사항들
Beta Was this translation helpful? Give feedback.
All reactions