avatarRyan Adhitama Putra

Summary

The webpage provides a comprehensive guide on integrating SWR and Axios for efficient data fetching in Next.js applications.

Abstract

The article delves into the integration of SWR (Stale-While-Revalidate) and Axios within a Next.js framework to streamline data fetching processes. It outlines the necessary steps to set up a project, including installing dependencies like Yarn, Visual Studio Code, SWR, and Axios, and configuring environment variables for API endpoints. The guide emphasizes the importance of managing configuration settings separately from the codebase for enhanced security and maintainability. It also demonstrates how to create an Axios instance for consistent HTTP requests and introduces a custom React hook using SWR for reactive data fetching with automatic revalidation. The tutorial concludes with practical implementation examples and encourages developers to connect on LinkedIn for further engagement with the community.

Opinions

  • The author suggests that combining Next.js with SWR and Axios can significantly improve the performance and efficiency of data fetching in web applications.
  • The use of a .env file is recommended for managing sensitive information, which the author believes enhances security and maintainability.
  • By providing a full source code link, the author implies that hands-on practice and reference to the code will aid in understanding the concepts better.
  • The article promotes the SWR library's ability to automatically revalidate data, which is seen as a beneficial feature for keeping data fresh in web applications.
  • The author encourages reader engagement by inviting them to clap, follow, and connect on various platforms, indicating a community-driven approach to learning and development.

Effortless Next.js Data Fetching with SWR, and Axios

In the fast-paced world of web development, data fetching plays a pivotal role in building dynamic and responsive web applications.

Developers are continually seeking ways to simplify this process while ensuring that their applications remain performant and efficient. Enter Next.js, SWR (Stale-While-Revalidate), and Axios — a triumphant trio that empowers developers to fetch and manage data with unprecedented ease.

In this article, we embark on a journey into the realm of Next.js, SWR, and Axios, exploring how this combination can revolutionize data fetching in your Next.js applications.

Requirement:

Before we proceed further, let’s make sure we have the necessary software.

Software:

1. Setup Project

Run the following command in your terminal/cmd

$ yarn create next-app next-swr-axios

2. Install Dependencies

You now have a new directory called next-swr-axios. Let’s cd into it:

$ cd next-swr-axios

Next, install dependencies

$ yarn add swr axios

Explanation :

  • swr : a React Hooks library for data fetching
  • axios : a promise-based HTTP Client for node.js and the browser.

3. Configure Environment

By using a .env file, you can easily manage and update configuration settings without hardcoding them in your code.

This approach enhances security and maintainability since sensitive information is kept separate from your source code and can be easily changed as needed without altering the application's codebase.

Additionally, the NEXT_PUBLIC_ prefix in this variable suggests that it is intended to be accessible on the client-side in a Next.js application, making it available to both the server and the browser.

Create .env file, and copy-paste this code below

NEXT_PUBLIC_API_HOST=https://crudcrud.com/api/184e182f1da846188b9abcd101b8c20b

4. Keep configuration settings in a separate file

Create ./src/config/index.js, and copy-paste this code below

const config = {
  API_HOST: process.env.NEXT_PUBLIC_API_HOST
};

export default config;

5. Create Axios Instance

Create ./src/libs/utils/api.js, and copy-paste this code below

import axios from 'axios';
import config from '@/config';

const instance = axios.create({
  baseURL: config.API_HOST,
  timeout: 40000,
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json; charset=utf-8'
  }
});

export const fetcher = (url) => {
  return instance.get(url).then((res) => {
    if (!res.data) {
      throw Error(res.data.message);
    }

    return res.data;
  });
};

export default instance;
  • An axios instance is created using axios.create(). This instance allows you to define default configurations for your HTTP requests.
  • baseURL is set to config.API_HOST, which specifies the base URL for all requests made with this instance. This can be useful for avoiding redundancy in your API URLs.
  • A timeout of 40,000 milliseconds (40 seconds) is set, which means that if a request takes longer than this time, it will be considered a timeout.
  • Default headers are specified to ensure consistency in request headers, such as specifying the Accept and Content-Type headers for JSON requests.

5. Create hooks for fetching data

Create ./src/libs/hooks/unicorn.js, and copy-paste this code below

import useSWR from 'swr';
import { fetcher } from '@/libs/utils/api';

export const useUnicorns = () => {
  const pathKey = `/unicorns`;
  const { data, error } = useSWR(pathKey, fetcher, {
    refreshInterval: 10000
  });

  return { data: data || [], loading: !error && !data };
};
  • The code imports the useSWR hook from the 'swr' library. This hook is used for data fetching with SWR.
  • It also imports the fetcher function from the api module, which is likely the function responsible for making HTTP requests using Axios.

useSWR is called with three arguments:

  • pathKey: This is the key representing the data you want to fetch. It's used to identify and cache the data.
  • fetcher: This is likely a function responsible for making the actual HTTP request to fetch the data. It's provided to useSWR as a callback.
  • { refreshInterval: 10000 }: This is an optional configuration object that specifies a refresh interval of 10,000 milliseconds (10 seconds). It means that SWR will automatically revalidate (refetch) the data every 10 seconds, keeping it up to date.

useSWR returns an object with two properties:

  • data: This is the fetched data. If the data has not been fetched yet, it will be undefined initially.
  • error: This holds any error that might occur during the data fetching process.

The useUnicorns custom hook returns an object with two properties:

  • data: This property contains the fetched data if it's available. If the data is still loading or has not been fetched yet, it defaults to an empty array ([]).
  • loading: This is a boolean that is true when neither an error nor data is present. It's false when data is available or an error has occurred.

6. Implement into Page

Copy-paste this code below into ./src/index.js

import { useUnicorns } from "@/libs/hooks/unicorn";

export default function Home() {
  const { data } = useUnicorns();
  return (
    <div>
      {data?.map((item) => (
        <div>{item?.name}</div>
      ))}
    </div>
  );
}

This code is a React component that fetches data using a custom hook called useUnicorns and then renders that data in a page named Home.

7. Result

Run the following command

$ yarn dev

Then your result will looks like this

Full source code : https://github.com/ryanadhitama/next-swr-axios/pull/1/files

Conclusion

Today, we learned how to integrate swr and axios in your Next.js project. We hope this tutorial will help other developers to make data fetching in Next.js project. Stay updated with our various other tutorials, and let’s connect on LinkedIn!

LinkedIn: https://www.linkedin.com/in/ryanadhitama/

In Plain English

Thank you for being a part of our community! Before you go:

Next
Swr
Axios
React
Recommended from ReadMedium