18.3.2.4 리팩토링

    이제 반복되는 코드를 따로 함수화하여 리팩토링해 봅시다. 이전에 thunk 함수를 위해 createRequestThunk라는 함수를 만들었던 것처럼 createRequestSaga라는 함수를 만들겠습니다.

    lib/createRequestSaga.js

    import { call, put } from 'redux-saga/effects';
    import { startLoading, finishLoading } from '../modules/loading';
    
    export default function createRequestSaga(type, request) {
      const SUCCESS = `${type}_SUCCESS`;
      const FAILURE = `${type}_FAILURE`;
    
      return function*(action) {
        yield put(startLoading(type)); // 로딩 시작
        try {
          const response = yield call(request, action.payload);
          yield put({
            type: SUCCESS,
            payload: response.data
          });
        } catch (e) {
          yield put({
            type: FAILURE,
            payload: e,
            error: true
          });
        }
        yield put(finishLoading(type)); // 로딩 
      };
    }

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.