Fetch data using SWR - Next.js
Swapnil Sharma / April 05, 2022
2 min read
SWR
SWR is a React Hooks library for remote data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
This is important for specific pages which can be left open and the data will remain fresh. If you re-focus or switch between tabs, SWR will automatically revalidate data.
To use SWR, we can import the hook and define which route to fetch.
import useSWR from 'swr';
const { data } = useSWR('/api/unsplash', fetcher);
fetcher
is a small wrapper around fetch
returning json
.
export default async function (...args) {
const res = await fetch(...args);
return res.json();
}
data
will contain the JSON response from our API route.
// /api/unsplash
{
"downloads": 7995,
"views": 1134429
}
Consuming the Data
Now that you have access to the data from the route, you can build a UI to consume the data. I've chosen to create "cards" for each metric.
import React from 'react';
import useSWR from 'swr';
import fetcher from '../../lib/fetcher';
import MetricCard from './card';
function Unsplash() {
const { data } = useSWR('/api/unsplash', fetcher);
const downloads = new Number(data?.downloads);
const views = new Number(data?.views);
const link = 'https://unsplash.com/@leerob';
return (
<>
<MetricCard header="Unsplash Downloads" link={link} metric={downloads} />
<MetricCard header="Unsplash Views" link={link} metric={views} />
</>
);
}
export default Unsplash;
Subscribe to the newsletter
Get emails from me about web development, tech, and early access to new articles.