Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* IMPORT */
- import {useRef} from 'react';
- import useMounted from 'react-use-mounted';
- import {useForceUpdate} from '@ui/hooks';
- /* TYPES */
- type StateLoading = {
- loading: true,
- error?: undefined,
- value?: undefined
- };
- type StateError = {
- loading: false,
- error: Error,
- value?: undefined
- };
- type StateSuccess<T> = {
- loading: false,
- error?: undefined,
- value: T
- };
- type State<T> = StateLoading | StateError | StateSuccess<T>;
- /* USE PROMISE */
- const usePromise = <T> ( promise: Promise<T> ): State<T> => {
- const mounted = useMounted (),
- forceUpdate = useForceUpdate (),
- promiseRef = useRef<Promise<T>> (),
- stateRef = useRef<State<T>> ({ loading: true });
- if ( promise !== promiseRef.current ) {
- promiseRef.current = promise;
- stateRef.current = { loading: true };
- const onSuccess = ( value: T ): void => {
- if ( !mounted.current || promise !== promiseRef.current ) return;
- stateRef.current = { loading: false, value };
- forceUpdate ();
- };
- const onError = ( error: Error ): void => {
- if ( !mounted.current || promise !== promiseRef.current ) return;
- stateRef.current = { loading: false, error };
- forceUpdate ();
- };
- promise.then ( onSuccess, onError );
- }
- return stateRef.current;
- };
- /* EXPORT */
- export default usePromise;
Advertisement
Add Comment
Please, Sign In to add comment