Polling

Ask a server again and again, at intervals its answers set. Backing off and stopping are both return values of poll.

On this page

What poll returns

thread-status.tsx
usePolling(threadId, async (id, signal) => {
  const response = await fetch(`/api/threads/${id}`, { signal });
  const thread = await parseThread(response);
  if (thread.status === 'running') return 2000;
Asks again in two seconds
  onSettled(thread);
  return null;
Stops polling
});

usePolling(key, poll) calls poll once the component mounts, then again as many milliseconds later as it resolves to, until it resolves to null.

Each answer sets the wait until the next call, so backing off after a failure, or asking sooner while something is about to finish, is a return value.

poll is the latest render’s, so it reads current props and state. The key it receives is the one this round started with.

The key

thread-status.tsx
const key = mode === null ? null : `${threadId}:${mode}`;

usePolling(key, poll);

A new key aborts the call in flight through signal and starts again, and null stops polling. The example asks nothing while mode is null.

A key is a string, a number or a boolean, compared with Object.is. An object made during render would restart polling every render, so it is a type error. Build a string from what should restart it.

Failures

thread-status.tsx
usePolling(threadId, async (id, signal) => {
  try {
    const response = await fetch(`/api/threads/${id}`, { signal });
    onUpdate(await parseThread(response));
    return 2000;
  } catch {
    return 10_000;
  }
});

A rejected poll stops polling, and the component fails with that error in its next render, for the nearest error boundary.

So does a poll that resolves to a negative or non-finite number, with an error starting with usePolling: poll must resolve to a non-negative number of milliseconds or null.

To keep polling after a failure, catch it inside poll and return the delay, as above.

k8ordo

React libraries that use Baseline features without holding back.