條件式獲取
條件式
使用 null
或傳遞一個函式作為 key
來條件式地獲取資料。如果該函式拋出錯誤或返回一個假值,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'
}