Guest User

Untitled

a guest
May 18th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. /* IMPORT */
  3.  
  4. import {useRef} from 'react';
  5. import useMounted from 'react-use-mounted';
  6. import {useForceUpdate} from '@ui/hooks';
  7.  
  8. /* TYPES */
  9.  
  10. type StateLoading = {
  11.   loading: true,
  12.   error?: undefined,
  13.   value?: undefined
  14. };
  15.  
  16. type StateError = {
  17.   loading: false,
  18.   error: Error,
  19.   value?: undefined
  20. };
  21.  
  22. type StateSuccess<T> = {
  23.   loading: false,
  24.   error?: undefined,
  25.   value: T
  26. };
  27.  
  28. type State<T> = StateLoading | StateError | StateSuccess<T>;
  29.  
  30. /* USE PROMISE */
  31.  
  32. const usePromise = <T> ( promise: Promise<T> ): State<T> => {
  33.  
  34.   const mounted = useMounted (),
  35.         forceUpdate = useForceUpdate (),
  36.         promiseRef = useRef<Promise<T>> (),
  37.         stateRef = useRef<State<T>> ({ loading: true });
  38.  
  39.   if ( promise !== promiseRef.current ) {
  40.  
  41.     promiseRef.current = promise;
  42.     stateRef.current = { loading: true };
  43.  
  44.     const onSuccess = ( value: T ): void => {
  45.  
  46.       if ( !mounted.current || promise !== promiseRef.current ) return;
  47.  
  48.       stateRef.current = { loading: false, value };
  49.  
  50.       forceUpdate ();
  51.  
  52.     };
  53.  
  54.     const onError = ( error: Error ): void => {
  55.  
  56.       if ( !mounted.current || promise !== promiseRef.current ) return;
  57.  
  58.       stateRef.current = { loading: false, error };
  59.  
  60.       forceUpdate ();
  61.  
  62.     };
  63.  
  64.     promise.then ( onSuccess, onError );
  65.  
  66.   }
  67.  
  68.   return stateRef.current;
  69.  
  70. };
  71.  
  72. /* EXPORT */
  73.  
  74. export default usePromise;
Advertisement
Add Comment
Please, Sign In to add comment