'use client' import { useState, useCallback } from 'react' import { AxiosError, AxiosRequestConfig } from 'axios' import { apiClient } from '../api' export interface UseApiOptions { onSuccess?: (data: any) => void onError?: (error: Error) => void } export interface UseApiReturn { data: T | null error: Error | null isLoading: boolean execute: (config: AxiosRequestConfig) => Promise reset: () => void } export function useApi(options?: UseApiOptions): UseApiReturn { const [data, setData] = useState(null) const [error, setError] = useState(null) const [isLoading, setIsLoading] = useState(false) const execute = useCallback( async (config: AxiosRequestConfig): Promise => { setIsLoading(true) setError(null) try { const response = await apiClient.request(config) setData(response.data) if (options?.onSuccess) { options.onSuccess(response.data) } return response.data } catch (err) { const error = err as AxiosError const errorMessage = error.response?.data ? JSON.stringify(error.response.data) : error.message const finalError = new Error(errorMessage) setError(finalError) if (options?.onError) { options.onError(finalError) } return null } finally { setIsLoading(false) } }, [options] ) const reset = useCallback(() => { setData(null) setError(null) setIsLoading(false) }, []) return { data, error, isLoading, execute, reset, } }