PromiseReducer.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. export const PromiseReducer = (state = {}, { type, status, payload, error, name }) => {
  2. if (type === 'PROMISE') {
  3. return {
  4. ...state,
  5. [name]: { status, payload, error }
  6. }
  7. }
  8. if (type === 'PROMISE_REMOVE') {
  9. let { [name]: remove, ...newState } = state
  10. return {
  11. ...newState
  12. }
  13. }
  14. return state
  15. }
  16. const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
  17. const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
  18. const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
  19. export const actionClearPromise = (name) => ({ type: 'PROMISE_REMOVE', status: 'RESOLVED', name})
  20. export const actionPromise = (name, promise) =>
  21. async dispatch => {
  22. dispatch(actionPending(name))
  23. try {
  24. let data = await promise
  25. dispatch(actionResolved(name, data))
  26. return data
  27. } catch (error) {
  28. dispatch(actionRejected(name, error))
  29. }
  30. }