import { useCallback, useEffect, useRef, useState } from 'react'; import { API } from '../../helpers'; import { parsePayPalQuote } from '../../helpers/paypalPayment'; // Bind quotes to the exact selection and coalesce preview/confirmation requests. export default function usePayPalQuote(endpoint, body, enabled, orgId) { const key = JSON.stringify([endpoint, body, orgId]); const currentKey = useRef(key); currentKey.current = key; const pending = useRef(null); const [result, setResult] = useState(null); const [loadingKey, setLoadingKey] = useState(null); const setQuote = (quote) => setResult({ key, quote }); const refresh = useCallback(() => { if (pending.current?.key === key) return pending.current.promise; const [url, payload, organization] = JSON.parse(key); setLoadingKey(key); setResult(null); const promise = API.post( url, payload, organization === undefined || organization === null ? undefined : { headers: { 'X-Org-Id': String(organization) } }, ) .then((response) => { if (!response.data.success) throw new Error(response.data.message); const quote = parsePayPalQuote(response); if (currentKey.current !== key) return null; setResult({ key, quote }); return quote; }) .finally(() => { if (pending.current?.promise === promise) pending.current = null; setLoadingKey((previous) => (previous === key ? null : previous)); }); pending.current = { key, promise }; return promise; }, [key]); useEffect(() => { if (enabled) refresh().catch(() => {}); }, [enabled, refresh]); return { quote: result?.key === key ? result.quote : null, setQuote, loading: enabled && loadingKey === key, refresh, }; }