examples/swr-site/content/en/docs/data-fetching.mdx
import { Callout } from 'nextra/components'
const { data, error } = useSWR(key, fetcher)
This is the very fundamental API of SWR. The fetcher here is an async function
that accepts the key of SWR, and returns the data.
The returned value will be passed as data, and if it throws, it will be caught
as error.
You can use any library to handle data fetching, for example a 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)
// ...
}
New Built-In Polyfills: fetch(), URL, and Object.assign
</Callout>import axios from 'axios'
const fetcher = url => axios.get(url).then(res => res.data)
function App() {
const { data, error } = useSWR('/api/data', fetcher)
// ...
}
Or using GraphQL with libs like graphql-request:
import { request } from 'graphql-request'
const fetcher = query => request('/api/graphql', query)
function App() {
const { data, error } = useSWR(
/* GraphQL */ `
{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}
`,
fetcher
)
// ...
}
If you want to pass variables to a GraphQL query, check out Multiple Arguments.