mirror of
https://github.com/router-for-me/Cli-Proxy-API-Management-Center.git
synced 2026-02-18 10:40:50 +08:00
feat: initialize new React application structure with TypeScript, ESLint, and Prettier configurations, while removing legacy files and adding new components and pages for enhanced functionality
This commit is contained in:
65
src/hooks/useApi.ts
Normal file
65
src/hooks/useApi.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 通用 API 调用 Hook
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useNotificationStore } from '@/stores';
|
||||
|
||||
interface UseApiOptions<T> {
|
||||
onSuccess?: (data: T) => void;
|
||||
onError?: (error: Error) => void;
|
||||
showSuccessNotification?: boolean;
|
||||
showErrorNotification?: boolean;
|
||||
successMessage?: string;
|
||||
}
|
||||
|
||||
export function useApi<T = any, Args extends any[] = any[]>(
|
||||
apiFunction: (...args: Args) => Promise<T>,
|
||||
options: UseApiOptions<T> = {}
|
||||
) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const { showNotification } = useNotificationStore();
|
||||
|
||||
const execute = useCallback(
|
||||
async (...args: Args) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await apiFunction(...args);
|
||||
setData(result);
|
||||
|
||||
if (options.showSuccessNotification && options.successMessage) {
|
||||
showNotification(options.successMessage, 'success');
|
||||
}
|
||||
|
||||
options.onSuccess?.(result);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorObj = err as Error;
|
||||
setError(errorObj);
|
||||
|
||||
if (options.showErrorNotification !== false) {
|
||||
showNotification(errorObj.message, 'error');
|
||||
}
|
||||
|
||||
options.onError?.(errorObj);
|
||||
throw errorObj;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[apiFunction, options, showNotification]
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setData(null);
|
||||
setError(null);
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
return { data, loading, error, execute, reset };
|
||||
}
|
||||
Reference in New Issue
Block a user