BlueWallet/hooks/useAsyncPromise.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-10-22 00:51:33 +02:00
import { useState, useEffect } from 'react';
/**
* A custom React hook that accepts a promise and returns the resolved value and any errors that occur.
*
* @template T - The type of the resolved value.
2023-10-22 14:25:48 +02:00
* @param {() => Promise<T>} promiseFn - A function that returns the promise to be resolved.
2023-10-22 00:51:33 +02:00
* @returns {{ data: T | null, error: Error | null, loading: boolean }} - An object with the resolved data, any error, and loading state.
*/
2023-10-22 14:25:48 +02:00
function useAsyncPromise<T>(promiseFn: () => Promise<T>) {
2023-10-22 00:51:33 +02:00
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
let isMounted = true;
2023-10-22 14:25:48 +02:00
promiseFn()
2023-10-22 00:51:33 +02:00
.then(result => {
if (isMounted) {
setData(result);
setLoading(false);
}
})
2023-12-25 22:22:49 +01:00
.catch((err: Error) => {
2023-10-22 00:51:33 +02:00
if (isMounted) {
setError(err);
setLoading(false);
}
});
return () => {
isMounted = false;
};
2023-10-22 14:25:48 +02:00
}, [promiseFn]);
2023-10-22 00:51:33 +02:00
return { data, error, loading };
}
export default useAsyncPromise;