shadcn-ahooks
useRequest

Polling

The API useRequest

Polling

By setting options.pollingInterval, enter the polling mode, useRequest will periodically trigger service execution.

const { data, run, cancel } = useRequest(getUsername, {
  pollingInterval: 3000,
});

For example, in the above scenario, getUsername will be requested every 3000ms. You can stop polling by cancel and start polling by run/runAsync.

You can experience the effect through the following example

Polling error retry

Polling by options. PollingErrorRetryCount configuration error retry count.

const { data, run, cancel } = useRequest(getUsername, {
  pollingInterval: 3000,
  pollingErrorRetryCount: 3,
});

You can experience the effect through the following example.

API

Return

PropertyDescriptionType
runStart polling(...params: TParams) => void
runAsyncStart polling(...params: TParams) => Promise<TData>
cancelStop polling() => void

Options

PropertyDescriptionTypeDefault
pollingIntervalPolling interval, in milliseconds. If the value is greater than 0, the polling mode is activated.number0
pollingWhenHiddenWhether to continue polling when the page is hidden. If set to false, polling will be temporarily paused when the page is hidden, and resume when the page is visible again.booleantrue
pollingErrorRetryCountNumber of polling error retries. If set to -1, an infinite number of timesnumber-1
pollingIntervalWhenChange the polling interval dynamically based on the result of the request.(data: TData, error: Error) => number-

Remark

  • options.pollingInterval, options.pollingWhenHidden support dynamic changes.
  • If you set options.manual = true, the initialization will not start polling, you need start it by run/runAsync.
  • If the pollingInterval changes from 0 to a value greater than 0, polling will not start automatically, and you need start it by run/runAsync.
  • The polling logic is to wait for pollingInterval time after each request is completed, and then initiate the next request.

On this page