// The server's price for a cart, asked again shortly after it changes (plan steps 3.3a, 6.9). // `fetchQuote(lines)` is the app's call (the counter: /api/pos/quote; the manager and the phones: // /api/orders/quote; the menu tablet: its own). Only the latest answer counts. import { useEffect, useRef, useState } from 'react' const QUOTE_DELAY_MS = 120 export function useQuote(fetchQuote, lines, extraKey = '') { const [state, setState] = useState({ quote: null, pending: false, error: null }) const seq = useRef(0) const fn = useRef(fetchQuote) useEffect(() => { fn.current = fetchQuote }) const key = JSON.stringify([lines, extraKey]) useEffect(() => { const mine = ++seq.current if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined } // eslint-disable-line react-hooks/set-state-in-effect setState(s => ({ ...s, pending: true })) const id = setTimeout(async () => { try { const data = await fn.current(lines) if (mine === seq.current) setState({ quote: data, pending: false, error: null }) } catch (err) { if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err })) } }, QUOTE_DELAY_MS) return () => clearTimeout(id) }, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is the lines + the caller's extra key return state }