promiseReducer.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import {all, takeEvery, put, call} from 'redux-saga/effects';
  2. export function promiseReducer(state = {}, { type, status, payload, error, name }) {
  3. if (type === 'PROMISE') {
  4. return {
  5. ...state,
  6. [name]: { status, payload, error }
  7. }
  8. }
  9. return state;
  10. }
  11. const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
  12. const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
  13. const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
  14. export const actionPromise = (name, promise) =>
  15. ({type: 'PROMISE_START', name, promise})
  16. export function* promiseWorker(action){ //это типа actionPromise который thunk
  17. const {name, promise} = action
  18. yield put(actionPending(name))
  19. try {
  20. let data = yield promise
  21. yield put(actionResolved(name, data))
  22. return data
  23. }
  24. catch (error) {
  25. yield put(actionRejected(name, error))
  26. }
  27. }
  28. export function* promiseWatcher(){
  29. yield takeEvery('PROMISE_START', promiseWorker)
  30. }