Create a Dashboard with Next.js API Routes - Fetching Data with SWR

👳🏽‍♂️

Ekam Singh / February 24, 2020

2 min read

In this series, you will learn how to create a dashboard using Next.js API routes and integrate with third-party APIs.

Overview

In the first three parts of the series, we learned how to fetch data from a variety of APIs. Now, we can consume this data visually to build our dashboard.

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 our dashboard page because it 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.

components/metrics/Unsplash.js
import React from 'react';
import useSWR from 'swr';
import format from 'comma-number';

import fetcher from '../../lib/fetcher';

import MetricCard from './card';

function Unsplash() {
  const { data } = useSWR('/api/unsplash', fetcher);

  const downloads = format(data?.downloads);
  const views = format(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;

Note: The MetricCard source code is here.

Example

The two cards below talk to /api/unsplash and pull back stats about my Unsplash account.

Conclusion

This concludes my series on creating a dashboard with Next.js API routes. If you missed the previous posts, they are linked below.

Create a Dashboard with Next.js API Routes

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

- subscribers – 28 issues