Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function useSendForm(sendForm) {
  2.   const FORM_SENDING = 'FORM_SENDING';
  3.   const FORM_SEND_FAILED = 'FORM_SEND_FAILED';
  4.   const FORM_SEND_SUCCEEDED = 'FORM_SEND_SUCCEEDED';
  5.  
  6.   const initialState = { sending: false, error: null, success: false };
  7.  
  8.   function reducer(state, action) {
  9.     switch (action.type) {
  10.       case FORM_SENDING:
  11.         return { sending: true, error: null, success: false };
  12.       case FORM_SEND_FAILED:
  13.         return { sending: false, error: action.error, success: false };
  14.       case FORM_SEND_SUCCEEDED:
  15.         return { sending: false, error: null, success: true };
  16.       default:
  17.         throw new Error();
  18.     }
  19.   }
  20.  
  21.   const [state, dispatch] = useReducer(reducer, initialState);
  22.  
  23.   return {
  24.     state,
  25.     doSendForm: async () => {
  26.       dispatch({ type: FORM_SENDING });
  27.       try {
  28.         await sendForm();
  29.         dispatch({ type: FORM_SEND_SUCCEEDED });
  30.       } catch (exception) {
  31.         dispatch({ type: FORM_SEND_FAILED, error: exception });
  32.       }
  33.     }
  34.   };
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement