import { useCallback, useEffect, useRef, useState, type DependencyList } from 'react'; export interface AsyncState { data: T | undefined; error: unknown; loading: boolean; reload: () => void; setData: (update: T | ((prev: T | undefined) => T | undefined)) => void; } /** * داده‌ای که از سرور می‌آید، با حالت‌های بارگذاری/خطا و «دوباره». * پاسخِ درخواستِ کهنه (بعد از عوض شدنِ deps) نادیده گرفته می‌شود. */ export function useAsync(load: () => Promise, deps: DependencyList): AsyncState { const [data, setData] = useState(undefined); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [nonce, setNonce] = useState(0); const loadRef = useRef(load); loadRef.current = load; useEffect(() => { let alive = true; setLoading(true); setError(null); loadRef.current().then( (value) => { if (!alive) return; setData(value); setLoading(false); }, (err: unknown) => { if (!alive) return; setError(err); setLoading(false); }, ); return () => { alive = false; }; }, [...deps, nonce]); const reload = useCallback(() => setNonce((n) => n + 1), []); return { data, error, loading, reload, setData }; }