redux에선 액션(Action), 슬라이스(Slice), Thunk가 있다.
액션(Action)
// base
import { createAction } from '@reduxjs/toolkit';
// default
export const AUTH = 'auth';
export const AUTH_SLICE_NAME = `${AUTH}Slice`;
// action
const AUTH_USER_LOGIN = `${AUTH}/userLogin`;
// createAction
const userLoginAction = createAction(AUTH_USER_LOGIN);
// actions
export const actions = {
userLoginAction,
};
슬라이스(Slice)
// base
import { createSlice } from '@reduxjs/toolkit';
import { AUTH_SLICE_NAME } from '../actions/auth.action';
// thunks
import { userLogin } from '../thunks/auth.thunk';
// initialState
const initialState = {
userInfo: undefined,
};
// createSlice
const authSlice = createSlice({
name: AUTH_SLICE_NAME,
initialState,
reducers: {},
extraReducers: builder => {
builder
.addCase(userLogin.fulfilled, (state, action) => {
const { userId, ACCESS_TOKEN, REFRESH_TOKEN } = action.payload;
state.userInfo = { userId, ACCESS_TOKEN, REFRESH_TOKEN };
});
},
});
export const auth = authSlice.name;
export const authReducer = authSlice.reducer;
export const authActions = authSlice.actions;
export default authSlice.reducer;
Thunk :
// base
import { createAsyncThunk } from '@reduxjs/toolkit';
// api
import { authApi } from '../apis/auth.api';
// action
import { actions } from '../actions/auth.action';
import { uiActions } from 'modules/ui';
// service
import { COOKIE_ACCESS_TOKEN, COOKIE_REFRESH_TOKEN } from 'services/cookie';
import { storageService } from 'services';
/**
* 로그인
*/
export const userLogin = createAsyncThunk(
actions.userLoginAction,
async (data, { dispatch, fulfillWithValue, rejectWithValue }) => {
try {
const res = await authApi.usersLogin(data);
console.log({ res });
const { userId, ACCESS_TOKEN, REFRESH_TOKEN } = res;
storageService.session.setItem(COOKIE_ACCESS_TOKEN, res.ACCESS_TOKEN);
return fulfillWithValue({
// code: res.code,
// isSuccess: res.isSuccess,
// message: res.message,
userId,
ACCESS_TOKEN,
REFRESH_TOKEN
});
} catch (error) {
return rejectWithValue(error);
}
}
);