gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

Redux-saga에서 반복되는 부분 모듈화 하기 #66

Open gloriaJun opened 4 years ago

gloriaJun commented 4 years ago

redux, loading, error와 어떻게 더 좋은 패턴으로 만들어나갈 수 있을 지.... 해당 부분에 대한 더 좋은 방법에 대해 아직도 고민 중이고, 시도 중이다. 키포인트는

  • 개발 당시나, 유지보수 시점이나 패턴으로 인하여 사람의 실수를 줄여나갈 수 있을지?
  • 불필요한 copy&paste를 줄일 수 있을 지..

관련하여 작성한 글 : https://gloriajun.github.io/frontend/2019/08/02/redux-saga-module.html

적용 전/후 코드 saga 비지니스 처리 로직 비교

AS-IS

function* fetchAccounts({ payload }) {
  const { pending, success, fail } = action.fetchAccounts;

  yield put(pending());
  try {
    const result = yield call(api.fetchAccounts, payload);
    yield put(success(result));
  } catch (error) {
    yield put(fail({ error }));
  }
}

TO-BE

function* fetchAccounts({ onSuccess, onError }) {
  const method = 'fetchAccounts';
  const result = yield call(api[method]);
  yield call(sagaCreator, action[method], result, onSuccess, onError);
}

References

이와 비슷한 고민에 대한 결과로 나온 다른 글들도 참고로..

function* apiSaga(api, asyncAction, options) {
  yield put(asyncAction.request())
  try {
    const payload = options && options.apiPayload
    const result = yield call(api, payload)
    yield put(asyncAction.success({ result }))
  } catch (error) {
    const failAction = asyncAction.fail({ error })
    yield call(errorHandler, failAction)
    yield put(failAction)
  }
}
export function* fetchNoticesSaga(action) {
  yield call(apiSaga, NoticesAPI.getNotices, fetchNotices, {
    apiPayload: action.payload,
  })
}