示例

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

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

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

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);
  // ...
}

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,请查看 多参数