promiseReducer.js 1.1 KB

12345678910111213141516171819202122232425262728
  1. export function promiseReducer(state = {}, { type, name, status, payload, error }) {
  2. if (type === 'PROMISE') {
  3. return {
  4. ...state,
  5. [name]: { status, payload: status === 'PROMISE' ? [name].payload : payload, error },
  6. };
  7. }
  8. if (type === 'PROMISE_CLEAR') {
  9. const { [name]: toRemove, ...newState } = state;
  10. return newState;
  11. }
  12. return state;
  13. }
  14. export const actionPending = (name) => ({ type: 'PROMISE', name, status: 'PENDING' });
  15. export const actionFulfilled = (name, payload) => ({ type: 'PROMISE', name, status: 'FULFILLED', payload });
  16. export const actionRejected = (name, error) => ({ type: 'PROMISE', name, status: 'REJECTED', error });
  17. export const actionPromiseClear = (name) => ({ type: 'PROMISE_CLEAR', name });
  18. export const actionPromise = (name, promise) => async (dispatch) => {
  19. dispatch(actionPending(name));
  20. try {
  21. let payload = await promise;
  22. dispatch(actionFulfilled(name, payload));
  23. return payload;
  24. } catch (error) {
  25. dispatch(actionRejected(name, JSON.parse(error.message)));
  26. }
  27. };