Step Level Up
Fetching Data with useSWR in TypeScript for Next.js
M
Mahadev Mandal

· min read

Fetching Data with useSWR in TypeScript for Next.js: A Complete Guide

Introduction

Fetching data efficiently is crucial in modern web development, especially when working with frameworks like Next.js and TypeScript. In this guide, we will explore how to use the useSwr hook to fetch data in a Next.js application written in TypeScript.

What is SWR?

SWR (stale-while-revalidate) is a React Hooks library for data fetching developed by Vercel. It provides a simple and efficient way to handle remote data fetching and caching, offering a better user experience by showing stale data while fetching fresh data in the background.

Why Use SWR?

  • Automatic Caching: SWR caches the data by default, reducing redundant network requests.
  • Revalidation: It revalidates the data in the background, ensuring that the UI always shows the most up-to-date information.
  • Focus Recovery: It automatically refetches data when the user refocuses the window.
  • TypeScript Support: Strong TypeScript support, ensuring type safety throughout your application.

Step-by-Step Guide

  1. Setting Up the Project
    First, set up a new Next.js project if you haven't already. Run the following commands to create a new project and install necessary dependencies:

    npx create-next-app@latest swr-typescript-nextjs --typescript
    cd swr-typescript-nextjs
    npm install swr
  2. Creating the Data Fetching Function
    Create a function to fetch data from an API. This function will use the Fetch API to get data and return the JSON response.
    const fetchData = async (url: string) => {
      const response = await fetch(url);
      return response.json();
    }

  3. Defining the Data Type
    Define the type for the data you are going to fetch. This helps in maintaining type safety.
    type DataType = {
      id: number;
      title: string;
      userId: number;
      body: string;
    }
  4. Using the useSWR Hook
    Create a React component that uses the useSWR hook to fetch data and handle loading and error states.
    'use client'
    import React from 'react';
    import useSWR from 'swr';
    
    const fetchData = async (url: string) => {
      const response = await fetch(url);
      return response.json();
    }
    
    type DataType = {
      id: number;
      title: string;
      userId: number;
      body: string;
    }
    
    const DataComponent: React.FC = () => {
      const { data, error } = useSWR<DataType[]>('https://jsonplaceholder.typicode.com/posts', fetchData);
    
      if (!data) return <div>Loading...</div>;
      if (error) return <div>Something went wrong.</div>;
    
      return (
        <div>
          <h1>All posts</h1>
          {data.map((item) => (
            <div key={item.id} style={{ border: '1px solid grey', marginTop: 10, padding: 10 }}>
              <h3>{item.title}</h3>
              <div dangerouslySetInnerHTML={{ __html: item.body }} />
            </div>
          ))}
        </div>
      );
    };
    
    export default DataComponent;
  5. Integrating the Component in Your Next.js Application
    Finally, integrate this component into your Next.js application by including it in one of your pages, such as index.tsx.
    import React from 'react';
    import DataComponent from '../components/DataComponent';
    
    const HomePage: React.FC = () => {
      return (
        <div>
          <h1>Welcome to My Blog</h1>
          <DataComponent />
        </div>
      );
    };
    
    export default HomePage;

Conclusion

Using useSWR in a Next.js project with TypeScript allows you to efficiently fetch and manage data. With features like caching, revalidation, and focus recovery, useSWR enhances the performance and user experience of your application. This guide covered the basics of setting up and using useSWR, helping you get started with data fetching in your Next.js projects.

Comments

Loading...

Mahadev Mandal

Written by Mahadev Mandal

I am a web developer with expertise in HTML, CSS, Tailwind, React.js, Next.js, Gatsby, API integration, WordPress, Netlify functions, the MERN stack, fullstack development, and NestJS.