Create A Example Handling Data Fetching With SWR In NextJS 13
Tags: nextjs, webdev, javascript, react
Published: 2023-09-26 03:10:32

Fetch data using **SWR in NextJS 13** . SWR ( Stale-While-Revalidate ) is a library for managing client-side data state in applications, commonly used applications, such as in React. When talking about SWR, we also refer to the commonly used name **RTX Query**
**RTK Query** : RTK Query is a powerful data storage and fetching tool. It is designed to simplify common scenarios for loading data in web applications, eliminating the need to write data fetching and caching logic yourself.
If you have time, please learn more, RTK Query is very good
Okay now I'll do a simple example
** INSTALL SWR IN PROJECT NEXTJS **
Here, I already have a NextJS project, so I installed swr. If you have not created a project yet, please see this article:  [Create A Project With Next.Js](https://hoanguyenit.com/create-a-project-with-nextjs.html)

```javascript
npm i swr
```
**CREATE FOLDER API IN PROJECT**
+**app/api/categories/route.tsx**: I created the **route.tsx** file and used typescript, depending on what people like

```javascript
import { NextResponse } from 'next/server'

export async function GET() {
  const res = await fetch(process.env.PATH_URL_BACKEND+'/api/categories', {
    headers: {
      'Content-Type': 'application/json',
    },
  })
  const result = await res.json()
  return NextResponse.json({ result })
}
 
```
The code above is simple, I just need to fetch the api to the backend server to get data

**process.env.PATH_URL_BACKEND** : is the domain path of the backend server: For example: _http://127.0.0.1:8000_ ,....or some other domain
+ Open the file **next.config.js** to configure the variables in **env**

```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
    env: {
        PATH_URL_BACKEND:"http://127.0.0.1:8000"
      },
    output: 'export',
}
module.exports = nextConfig
```
**IMPORT SWR IN COMPONENT**
Now you can create any component for yourself, because this job only requires the SWR library to use
+ **app/category/page.tsx** : 

```javascript
'use client'
import Link from "next/link";
import useSWR from "swr";
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Menu() {
  const { data, error, isLoading } = useSWR<any>(
    `/api/categories`,
    fetcher
  );

  if (error) return <div>Failed to load</div>;
  if (isLoading) return <div>Loading...</div>;
  if (!data) return null;
  return (
    <>
     <ul className="w-full bg-gray-400 flex flex-wrap">
                  {
                                  data &&  data.result.multiple?.length>0 && data.result.multiple.map(({slug,name,parent_id,id,children_categories} : any)=>{
                                        return (
                                            <li key = {id} className='px-2 py-1'>
                                                <Link href={`/category/`+slug}  className='text-black group-hover:text-[#bf1650]'>+ {name}</Link>
                                                <ul className="w-full pl-4">
                                                {
                                                children_categories?.length>0 && children_categories.map((item  : any)=>{
                                                        return <li key = {item.id} className=''><Link href={`/category/`+item.slug} className='text-red-500'>- {item.name}</Link></li>
                                                }) 
                                                
                                                }
                                                </ul>
                                            </li>
                                        )
                                    })
                                }
                  </ul>
    </>
  );
}
```
The above code has some things to do as follows:

+ Import swr trong component

```javascript
import useSWR from "swr";

```
+ Fetch data through fetch, usually we also need to fetch it first

```javascript
const fetcher = (url: string) => fetch(url).then((res) => res.json());
```
+ Call swr in function component

```javascript
const { data, error, isLoading } = useSWR<any>(
    `/api/categories`,
    fetcher
  );
```
**data **:   contains the data returned from the server when we use fetch, When the data is updated, the data will change and your UI will be updated automatically to reflect the new data, you can To customize it as follows for easy management: data: categories , then you just need to use the categories variable

**error** :  contains information about any errors that occurred during request sending or data processing. If there is no error, the value of error will be null .

**isLoading**:  is a boolean variable ( true or false ). If it is true , it means we are waiting for loading.... When the value is false , it means the fetch is finished, there is data, displayed just for users to see

Speaking of **useSWR **: we see above that it has two required parameters

userSWR(key,function, options) :

**Key** ( _must have parameter_ ): we need to provide a value to let it know which transmission line we need to request. Above I used  `/api/categories` , it is the path http://localhost:3000/api/categories in nextjs, when we npm run dev . When requested to that router , it will process the fetch in the file app/api/categories/route.tsx

**Function** ( _required parameter _): is the fetch api processing function, it receives the Key value and sends a request for processing.

**Options** (_optional_): an options object for the SWR hook
You can learn more here:  [SWR React Hooks for Data Fetching](https://swr.vercel.app/docs/api)
The article : [Create A Example Handling Data Fetching With SWR In NextJS 13](https://hoanguyenit.com/create-a-example-handling-data-fetching-with-swr-in-nextjs.html)