promiseReducer.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { put, takeEvery } from "redux-saga/effects";
  2. import { aboutMeWorker } from "../actions/actionAboutMe";
  3. import { pageStartWorker } from "../actions/actionPageStart";
  4. export function promiseReducer(state = {}, { type, name, status, payload, error }) {
  5. if (type === "PROMISE") {
  6. return {
  7. ...state,
  8. [name]: { status, payload: status === "PROMISE" ? [name].payload : payload, error },
  9. };
  10. }
  11. if (type === "PROMISE_CLEAR") {
  12. const { [name]: toRemove, ...newState } = state;
  13. return newState;
  14. }
  15. return state;
  16. }
  17. export const actionPending = (name) => ({ type: "PROMISE", name, status: "PENDING" });
  18. export const actionFulfilled = (name, payload) => ({ type: "PROMISE", name, status: "FULFILLED", payload });
  19. export const actionRejected = (name, error) => ({ type: "PROMISE", name, status: "REJECTED", error });
  20. export const actionPromiseClear = (name) => ({ type: "PROMISE_CLEAR", name });
  21. export const actionPromise = (name, promise) => ({ type: "PROMISE_START", name, promise });
  22. export function* promiseWorker(action) {
  23. const { name, promise } = action;
  24. yield put(actionPending(name));
  25. try {
  26. let data = yield promise;
  27. yield put(actionFulfilled(name, data));
  28. return data;
  29. } catch (error) {
  30. yield put(actionRejected(name, error));
  31. }
  32. }
  33. export function* promiseWatcher() {
  34. yield takeEvery("PROMISE_START", promiseWorker);
  35. yield takeEvery("PAGE_START", pageStartWorker);
  36. yield takeEvery("ABOUT_ME", aboutMeWorker);
  37. }