리엑트 블로그 만들기 5 - 리덕스 세팅하기

리엑트 블로그 만들기 5 - 리덕스 세팅하기

//LOGIN
export const LOGIN_REQUEST = "LOGIN_REQUEST";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAILURE = "LOGIN_FAILURE";

// CLEAR ERROR
export const CLEAR_ERROR_REQUEST = "CLEAR_REQUEST";
export const CLEAR_ERROR_SUCCESS = "CLEAR_SUCCESS";
export const CLEAR_ERROR_FAILURE = "CLEAR_FAILURE";
import {
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAILURE,
CLEAR_ERROR_REQUEST,
CLEAR_ERROR_SUCCESS,
CLEAR_ERROR_FAILURE,
} from "../types";

const initialState = {
token: localStorage.getItem("token"),
isAuthenticated: null,
isLoading: false,
user: "",
userId: "",
userName: "",
userRole: "",
errorMsg: "",
successMsg: "",
};

const authReducer = (state = initialState, action) => {
switch (action.type) {
case LOGIN_REQUEST:
return {
...state,
errorMsg: "",
};
case LOGIN_SUCCESS:
localStorage.setItem("token", action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
isLoading: false,
userId: action.payload.user.id,
userRole: action.payload.user.role,
errorMsg: "",
};
case LOGIN_FAILURE:
localStorage.removeItem("token");
return {
...state,
...action.payload,
token: null,
user: null,
userId: null,
userRole: null,
errorMsg: action.payload.data.msg,
};

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

export default authReducer;
Share