Implemented useAsync in the app structure for cleaner code

This commit is contained in:
2026-01-03 03:58:32 +01:00
parent 533e832e44
commit 2cc324c517
10 changed files with 177 additions and 182 deletions
+68
View File
@@ -0,0 +1,68 @@
import { useState, useEffect } from "react";
export function useAsync<T>(
defaultValue: T,
asyncFunction: () => Promise<T>,
dependencies: any[] = []
) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<null | Error>(null);
const [value, setValue] = useState<T>(defaultValue);
useEffect(() => {
let isMounted = true;
setLoading(true);
asyncFunction()
.then((result) => {
if (isMounted) setValue(result);
})
.catch((err) => {
if (isMounted) setError(err);
})
.finally(() => {
if (isMounted) setLoading(false);
});
return () => {
isMounted = false;
};
}, dependencies);
return { loading, error, value, setValue };
}
export function useAsyncInterval<T>(
defaultValue: T,
asyncFunction: () => Promise<T>,
interval: number,
dependencies: any[] = []
) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<null | Error>(null);
const [value, setValue] = useState<T>(defaultValue);
useEffect(() => {
let isMounted = true;
const iid = setInterval(() => {
setLoading(true);
asyncFunction()
.then((result) => {
if (isMounted) setValue(result);
})
.catch((err) => {
if (isMounted) setError(err);
})
.finally(() => {
if (isMounted) setLoading(false);
});
}, interval);
return () => {
isMounted = false;
clearInterval(iid);
};
}, dependencies);
return { loading, error, value, setValue };
}