ポーリング
ポーリングの概要
ポーリングは、指定された間隔でクエリを実行させることで「リアルタイム」効果を実現する機能を提供します。クエリのポーリングを有効にするには、`pollingInterval` にミリ秒単位の間隔を指定して `useQuery` フックまたはアクションクリエーターに渡します。
ヒント
ポーリングでは、ウィンドウがフォーカスされていないときにリクエストの送信をスキップすることもできます。 この動作を有効にするには、`skipPollingIfUnfocused: true` を `useQuery` フックまたはアクションクリエーターに渡します。
注: `skipPollingIfUnfocused` を使用するには、`setupListeners` を呼び出す必要があります。
src/Pokemon.tsx
import * as React from 'react'
import { useGetPokemonByNameQuery } from './services/pokemon'
export const Pokemon = ({ name }: { name: string }) => {
// Automatically refetch every 3s unless the window is out of focus
const { data, status, error, refetch } = useGetPokemonByNameQuery(name, {
pollingInterval: 3000,
skipPollingIfUnfocused: true,
})
return <div>{data}</div>
}
React Hooksを使用しないアクションクリエーターの場合
const { data, status, error, refetch } = store.dispatch(
endpoints.getCountById.initiate(id, {
subscriptionOptions: { pollingInterval: 3000 },
}),
)
React Hooksを使用しないポーリング
React Hooksの利便性なしでポーリングを使用する場合は、Promiseのrefに対して `updateSubscriptionOptions` を手動で呼び出して、間隔を更新する必要があります。 このアプローチはフレームワークによって異なりますが、どこでも可能です。 1つの可能性についてはSvelteの例を、サブスクリプションの手動操作の詳細についてはReact Hooksを使用しない場合の使用のページを参照してください。
queryRef.updateSubscriptionOptions({ pollingInterval: 0 })