"use client"; import { useCallback, useEffect, useState } from "react"; import { ApiError, apiFetch, unwrap } from "./api"; type Query = Record; // Generic GET-list hook. Unwraps `{ data: [...] }` and tolerates either a bare // array or a paginated object with a `data` field. export function useList( path: string | null, query?: Query, ): { data: T[]; loading: boolean; error: string | null; reload: () => void; } { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const queryKey = JSON.stringify(query ?? {}); const reload = useCallback(() => { if (!path) { // No path yet (e.g. a filter not chosen): show an empty, non-loading state. setData([]); setLoading(false); setError(null); return; } setLoading(true); setError(null); apiFetch(path, { query }) .then((res) => { const value = unwrap(res); setData(Array.isArray(value) ? (value as T[]) : []); }) .catch((e: unknown) => { setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات"); setData([]); }) .finally(() => setLoading(false)); // eslint-disable-next-line react-hooks/exhaustive-deps }, [path, queryKey]); useEffect(() => { reload(); }, [reload]); return { data, loading, error, reload }; } // Single-record GET hook. export function useItem(path: string | null): { data: T | null; loading: boolean; error: string | null; reload: () => void; } { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const reload = useCallback(() => { if (!path) { setData(null); setLoading(false); setError(null); return; } setLoading(true); setError(null); apiFetch(path) .then((res) => setData(unwrap(res))) .catch((e: unknown) => setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات"), ) .finally(() => setLoading(false)); }, [path]); useEffect(() => { reload(); }, [reload]); return { data, loading, error, reload }; }