Client-side data fetching with SWR

Tutorial 5 of 5

1. Introduction

Goal of the Tutorial

In this tutorial, we will be focusing on how to use SWR for client-side data fetching in Next.js applications.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand the importance of SWR in data fetching
- Use SWR for client-side data fetching in Next.js
- Implement SWR in real-world applications

Prerequisites

Before proceeding with this tutorial, you should have:
- Basic knowledge of JavaScript/ES6
- Basic understanding of Next.js
- Node.js and npm installed on your computer

2. Step-by-Step Guide

SWR is a React Hooks library for data fetching. It's built by Vercel, the company behind Next.js. SWR stands for "stale-while-revalidate", a HTTP cache invalidation strategy.

Installation

First, install the SWR package by running the following command in your terminal:

npm install swr

Basic Usage

To use SWR, you first need to import it in your file:

import useSWR from 'swr'

Then, you can use it within your functional component. Here's an example:

const fetcher = url => fetch(url).then(r => r.json())

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  return <div>Hello {data.name}!</div>
}

In the example above, useSWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

3. Code Examples

Example 1: Fetching data from an API

import useSWR from 'swr'

const fetcher = url => fetch(url).then(res => res.json())

function App() {
  const { data, error } = useSWR('https://api.github.com/repos/vercel/swr', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  // render data
  return <div>SWR stars: {data.stargazers_count}</div>
}

In this example, we are fetching the number of stars of the SWR repository on GitHub using the GitHub API. If there's an error while fetching the data, we render "Failed to load". If the data is not yet there, we render "Loading...". Once we have the data, we render the number of stars.

4. Summary

In this tutorial, we learned about SWR and how to use it for client-side data fetching in Next.js. We learned that SWR stands for "stale-while-revalidate", a cache invalidation strategy that allows us to have a fast and smooth user experience by returning the data from cache first, then sending the fetch request, and finally coming with the up-to-date data.

5. Practice Exercises

Exercise 1:

Create a Next.js application that fetches data from an API of your choice using SWR. Render the data on a page.

Exercise 2:

Add error handling to the application you created in Exercise 1. If there's an error while fetching the data, render a meaningful error message to the user.

Exercise 3:

Update the application from Exercise 2 to show a loading state while the data is being fetched. If the data is not yet available, render "Loading...". Once the data is there, render the data.

Solutions

  1. The solution will depend on the API you choose. Here's an example with the Pokémon API:
import useSWR from 'swr'

const fetcher = url => fetch(url).then(res => res.json())

function App() {
  const { data, error } = useSWR('https://pokeapi.co/api/v2/pokemon/ditto', fetcher)

  if (error) return <div>Failed to load Pokemon</div>
  if (!data) return <div>Loading...</div>

  return <div>{data.name}</div>
}
  1. The solution is included in the code above with the line if (error) return <div>Failed to load Pokemon</div>
  2. The solution is included in the code above with the line if (!data) return <div>Loading...</div>

Remember, the best way to learn is by doing. Keep practicing and experimenting with different APIs.