Skip to content

数据请求

{ data, error } = useSWR(key, fetcher)

这是 SWR 的基本 API。这里的 fetcher 是一个异步函数,它接受 SWR 的 key 并返回数据。

返回值将作为 data 传递,如果抛出错误,将作为 error 被捕获。

💡

注意:如果 fetcher全局配置提供的,可以从参数中忽略。

Fetch

你可以使用任何库来处理数据请求,比如一个 fetch polyfill developit/unfetch

import fetch from 'unfetch'
const fetcher = url => fetch(url).then(r => r.json())
function App () {
const { data, error } = useSWR('/api/data', fetcher)
// ...
}
💡

如果你使用的是 Next.js,则不需要 import 这个 polyfill:
新的内置 Polyfills: fetch()、URL、和Object.assign

Axios

import axios from 'axios'
const fetcher = url => axios.get(url).then(res => res.data)
function App () {
const { data, error } = useSWR('/api/data', fetcher)
// ...
}

GraphQL

或者配合类似 graphql-request 的库使用 GraphQL:

import { request } from 'graphql-request'
const fetcher = query => request('/api/graphql', query)
function App () {
const { data, error } = useSWR(
`{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}`,
fetcher
)
// ...
}

如果要把变量传递给 GraphQL query,请查看多个参数