feat: add axtios instanse and useApi hook

This commit is contained in:
Sajad Mirjalili
2025-08-14 16:37:00 +03:30
parent a4dde02804
commit c1439f5fe0
5 changed files with 113 additions and 35 deletions

24
src/hooks/useApi.ts Normal file
View File

@@ -0,0 +1,24 @@
import { useState } from 'react';
type ApiFunction<T, P> = (params?: P) => Promise<{ data: T }>;
export function useApi<T, P>(apiFunction: ApiFunction<T, P>) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
const execute = async (params?: P) => {
setLoading(true);
setError(null);
try {
const response = await apiFunction(params);
setData(response.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
return { data, loading, error, execute };
}