import { useState, useEffect, useCallback } from "react"; // Set by lib/session.tsx once a token is available; read synchronously here so // callers never have to await SecureStore before every request. let authToken: string | null = null; export const setAuthToken = (token: string) => { authToken = token; }; export const clearAuthToken = () => { authToken = null; }; export const fetchAPI = async (url: string, options?: RequestInit) => { try { const headers = new Headers(options?.headers); if (authToken && !headers.has("Authorization")) { headers.set("Authorization", `Bearer ${authToken}`); } const response = await fetch(url, { ...options, headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error("Fetch error:", error); throw error; } }; export const useFetch = (url: string, options?: RequestInit) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const result = await fetchAPI(url, options); setData(result.data); } catch (err) { setError((err as Error).message); } finally { setLoading(false); } }, [url, options]); useEffect(() => { fetchData(); }, [fetchData]); return { data, loading, error, refetch: fetchData }; };