리엑트 블로그 만들기 11 - 회원가입 리덕스 작업

리엑트 블로그 만들기 11 - 회원가입 리덕스 작업

const authReducer = (state = initialState, action) => {
switch (action.type) {
case REGISTER_REQUEST:
case LOGIN_REQUEST:
case LOGOUT_REQUEST:
return {
...state,
errorMsg: "",
isLoading: true
}
case REGISTER_SUCCESS:
case LOGIN_SUCCESS:
localStorage.setItem("token", action.payload.token)
return {
...state,
...action.payload,
isAuthenticated: true,
isLoading: false,
userId: action.payload.user.userId,
userRole: action.payload.user.role,
errorMsg: ""

}
case REGISTER_FAILURE:
case LOGOUT_FAILURE:
case LOGIN_FAILURE:
localStorage.removeItem("token")
return {
...state,
...action.payload,
token: null,
user: null,
userId: null,
isAuthenticated: false,
isLoading: false,
userRole: null,
errorMsg: action.payload.user.role
}
case LOGOUT_SUCCESS:
localStorage.removeItem("token")
return {
token: null,
user: null,
userId: null,
isAuthenticated: false,
isLoading: false,
userRole: null,
errorMsg: ""

};
case CLEAR_ERROR_REQUEST:
return {
...state,
errorMsg: null,
}
case CLEAR_ERROR_SUCCESS:
return {
...state,
errorMsg: null,
}
case CLEAR_ERROR_FAILURE:
return {
...state,
errorMsg: null
}

case USER_LOADING_REQUEST:
return {
...state,
isLoading: true
}
case USER_LOADING_SUCCESS:
return {
...state,
isAuthenticated: true,
isLoading: false,
user: action.payload,
userId: action.payload._id,
userName: action.payload.userName,
userRole: action.payload.role
}
case USER_LOADING_FAILURE:
return {
...state,
user: null,
isAuthenticated: false,
isLoading: false,
userRole: "",
}

default:
return state;
}
}
// Register
const registerUserAPI = (req) => {
console.log(req, "req");

return axios.post("api/user", req);
};

function* registerUser(action) {
try {
const result = yield call(registerUserAPI, action.payload);
console.log(result, "RegisterUser Data");
yield put({
type: REGISTER_SUCCESS,
payload: result.data,
});
} catch (e) {
yield put({
type: REGISTER_FAILURE,
payload: e.response,
});
}
}

function* watchRegisterUser() {
yield takeEvery(REGISTER_REQUEST, registerUser);
}
export default function* authSaga() {
yield all([
fork(watchLoginUser),
fork(watchLogoutUser),
fork(watchUserLoading),
fork(watchRegisterUser),
fork(watchClearError),
]);
}
Share