여기선 async를 쓰진 않지만 실제로 로그인 기능에선 async를 쓰기 때문에 이 부분도 Redux Middleware을 사용해서 바꿔보자
const Login = ({ setAuthenticate }) => {
const [id, setId] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
const dispatch = useDispatch();
const loginUser = (e) => {
e.preventDefault();
dispatch(authenticateAction.login(id, password));
navigate("/");
};
return (
<Container>
<Form onSubmit={loginUser}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
onChange={(e) => setId(e.target.value)}
/>
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="danger" type="submit">
로그인
</Button>
</Form>
</Container>
);
};
export default Login;
function login(id, password) {
return (dispatch, getState) => {
dispatch({ type: "LOGIN_SUCCESS", payload: { id, password } });
};
}
export const authenticateAction = { login };
let initialState = {
id: "",
password: "",
authenticate: false,
};
function authentiateReducer(state = initialState, action) {
let { type, payload } = action;
switch (type) {
case "LOGIN_SUCCESS":
return {
...state,
id: payload.id,
password: payload.password,
authenticate: true,
};
default:
return { ...state };
}
}
export default authentiateReducer;
여기까지만 하면 action까지는 되나, reducer까지는 못간다.
=> store.js에 productReducer만 적용되어 있기 때문
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import productReducer from "./reducers/productReducer"
let store = createStore(productReducer, applyMiddleware(thunk));
export default store;
=> reducer파일이 여러개가 되면 reducer들을 합쳐줘야 한다.
=> combineReducer
를 이용