RM / src /hooks /useApi.ts
trretretret's picture
Initial commit: Add research assistant application
b708f13
"use client";
import { useState, useCallback } from "react";
/**
* Generic API state returned from useApi
*/
export interface ApiState<T> {
execute: (data?: any) => Promise<T | undefined>;
data: T | null;
loading: boolean;
error: string | null;
}
/**
* useApi hook for on-demand API calls
* @param requestFn - function returning a Promise (e.g., axios.post or fetch)
*/
export function useApi<T = any>(requestFn: (data?: any) => Promise<T>): ApiState<T> {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<T | null>(null);
const execute = useCallback(
async (payload?: any) => {
setLoading(true);
setError(null);
try {
const response = await requestFn(payload);
setData(response);
setLoading(false);
return response;
} catch (err: any) {
setError(err?.message || "Unknown error");
setLoading(false);
}
},
[requestFn]
);
return { execute, data, loading, error };
}