跳至內容
文件
全域設定

全域設定

上下文 SWRConfig 可以為所有 SWR Hook 提供全域設定(選項)。

<SWRConfig value={options}>
  <Component/>
</SWRConfig>

在此範例中,所有 SWR Hook 將使用相同的 fetcher 來載入 JSON 資料,並且預設每 3 秒重新整理一次

import useSWR, { SWRConfig } from 'swr'
 
function Dashboard () {
  const { data: events } = useSWR('/api/events')
  const { data: projects } = useSWR('/api/projects')
  const { data: user } = useSWR('/api/user', { refreshInterval: 0 }) // override
 
  // ...
}
 
function App () {
  return (
    <SWRConfig 
      value={{
        refreshInterval: 3000,
        fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
      }}
    >
      <Dashboard />
    </SWRConfig>
  )
}

巢狀設定

SWRConfig 會合併來自父層上下文的設定。它可以接收物件或函式設定。函式設定會接收父層設定作為引數,並傳回您可以自行客製化的新設定。

物件設定範例

import { SWRConfig, useSWRConfig } from 'swr'
 
function App() {
  return (
    <SWRConfig
      value={{
        dedupingInterval: 100,
        refreshInterval: 100,
        fallback: { a: 1, b: 1 },
      }}
    >
      <SWRConfig
        value={{
          dedupingInterval: 200, // will override the parent value since the value is primitive
          fallback: { a: 2, c: 2 }, // will merge with the parent value since the value is a mergeable object
        }}
      >
        <Page />
      </SWRConfig>
    </SWRConfig>
  )
}
 
function Page() {
  const config = useSWRConfig()
  // {
  //   dedupingInterval: 200,
  //   refreshInterval: 100,
  //   fallback: { a: 2,  b: 1, c: 2 },
  // }
}

函式設定範例

import { SWRConfig, useSWRConfig } from 'swr'
 
function App() {
  return (
    <SWRConfig
      value={{
        dedupingInterval: 100,
        refreshInterval: 100,
        fallback: { a: 1, b: 1 },
      }}
    >
      <SWRConfig
        value={parent => ({
          dedupingInterval: parent.dedupingInterval * 5,
          fallback: { a: 2, c: 2 },
        })}
      >
        <Page />
      </SWRConfig>
    </SWRConfig>
  )
}
 
function Page() {
  const config = useSWRConfig()
  // {
  //   dedupingInterval: 500,
  //   fallback: { a: 2, c: 2 },
  // }
}

額外 API

快取提供者

除了列出的所有選項之外,SWRConfig 還接受一個可選的 provider 函式。請參閱快取章節以取得更多詳細資訊。

<SWRConfig value={{ provider: () => new Map() }}>
  <Dashboard />
</SWRConfig>

存取全域設定

您可以使用 useSWRConfig Hook 來取得全域設定,以及 mutatecache

import { useSWRConfig } from 'swr'
 
function Component () {
  const { refreshInterval, mutate, cache, ...restConfig } = useSWRConfig()
 
  // ...
}

巢狀設定會被擴充。如果沒有使用 <SWRConfig>,它將會傳回預設設定。