| import { useState, useCallback } from "react"; | |
| import { getErrorMessage } from "../api"; | |
| /** | |
| * Generic hook for API calls with loading/error/result state. | |
| * Eliminates the repeated try/catch/setLoading/setError pattern. | |
| */ | |
| export function useApiCall<T>() { | |
| const [data, setData] = useState<T | null>(null); | |
| const [loading, setLoading] = useState(false); | |
| const [error, setError] = useState(""); | |
| const run = useCallback(async (fn: () => Promise<T>): Promise<T | null> => { | |
| setLoading(true); | |
| setError(""); | |
| try { | |
| const result = await fn(); | |
| setData(result); | |
| return result; | |
| } catch (err) { | |
| setError(getErrorMessage(err)); | |
| return null; | |
| } finally { | |
| setLoading(false); | |
| } | |
| }, []); | |
| const clear = useCallback(() => { | |
| setData(null); | |
| setError(""); | |
| }, []); | |
| return { data, loading, error, setError, run, clear }; | |
| } | |