1 import { useCallback, useReducer, useRef } from 'react';
3 import useIsMounted from '@proton/hooks/useIsMounted';
5 const DEFAULT_STATE = {
9 const reducer = (state, action) => {
10 switch (action.type) {
20 result: action.payload,
27 error: action.payload,
32 const useAsync = (setResults = true) => {
33 const [{ loading, result, error }, dispatch] = useReducer(reducer, DEFAULT_STATE);
34 const isMounted = useIsMounted();
35 const promiseRef = useRef();
37 const run = useCallback(async (promise) => {
38 const isCurrentPromise = () => promiseRef.current === promise;
39 promiseRef.current = promise;
41 dispatch({ type: 'loading' });
43 const data = await promise;
44 if (isMounted() && isCurrentPromise()) {
45 dispatch({ type: 'success', payload: setResults ? data : undefined });
49 if (isMounted() && isCurrentPromise() && e.name !== 'AbortError') {
50 dispatch({ type: 'error', payload: setResults ? e : undefined });
64 export default useAsync;