コンテンツへスキップ
ドキュメント
条件付きデータフェッチ

条件付きフェッチ

条件付き

データを条件付きでフェッチするには、key として null を使用するか、関数を渡します。関数がエラーをスローするか、偽の値が返される場合、SWRはリクエストを開始しません。

// conditionally fetch
const { data } = useSWR(shouldFetch ? '/api/data' : null, fetcher)
 
// ...or return a falsy value
const { data } = useSWR(() => shouldFetch ? '/api/data' : null, fetcher)
 
// ...or throw an error when user.id is not defined
const { data } = useSWR(() => '/api/data?uid=' + user.id, fetcher)

依存

SWRでは、他のデータに依存するデータをフェッチすることもできます。これにより、最大の並列処理(ウォーターフォールを回避)が保証されるとともに、次のデータフェッチが発生するために動的データが必要な場合は、シリアルフェッチも保証されます。

function MyProjects () {
  const { data: user } = useSWR('/api/user')
  const { data: projects } = useSWR(() => '/api/projects?uid=' + user.id)
  // When passing a function, SWR will use the return
  // value as `key`. If the function throws or returns
  // falsy, SWR will know that some dependencies are not
  // ready. In this case `user.id` throws when `user`
  // isn't loaded.
 
  if (!projects) return 'loading...'
  return 'You have ' + projects.length + ' projects'
}