Example Of Using The GenerateStaticParams() In NextJs
Tags: nextjs, webdev, react, javascript
Published: 2023-09-26 02:48:21

How to use the  generateStaticParams function in NextJS 13. generateStaticParams is called at application build time, which means when the application runs, it will be called first. To have the data, it will Props params to the processing component to display the data.
I have the project folder structure as follows:

![Example Of Using The GenerateStaticParams() In NextJs - hoanguyenit.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6u1b3145nttz4l8h3ckn.png)
But I will briefly share how to use  generateStaticParams
**+ File layout.tsx**

```javascript
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import Post from './post/page'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Post />
        {children}
      </body>
    </html>
  )
}
```
In the layout.tsx file , I called Post component
So we need to create a route path:** src/app/post/page.tsx** . Used to display a list of articles

```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 Post() {
    const { data: posts, error, isLoading } = useSWR('/api/posts', fetcher)
 
    if (error) return <div>failed to load</div>
    if (isLoading) return <div>loading...</div>
   
    // render data
    return <div>

<ul className='w-full grid grid-cols-4 gap-2 lg:grid-cols-4'>
          {
                    posts.result && posts.result.data.map(({title,slug,content,id,image} : any )=>{
                        return(
                            <li key = {id} className='p-2 bg-white shadow-md rounded-sm transtion-all ease-in-out duration-300 hover:scale-105'>
                                
                                <h3><Link href={`/post/${id}`} className='text-gray-600 py-2 capitalize text-[13px] block transtion-all ease-in-out delay-100 hover:text-secondary-900'>{title}</Link></h3>
                              
                            </li>
                        )
                    })
                }	

          </ul>
    </div>
}
```
The code of the Post component uses the **swr **library . The swr library is very good, helping us easily request apis, and also easily check the returned data through the following values: { **data, errors, isLoading**}
If you have seen **RTK Query** , you can also see how to call **swr**. 
Above, because we called **api/post**, that means we also need to create a route for it: 
**+ app/api/post/route.tsx** : Used to return post list data, 

```javascript
import { NextRequest,NextResponse } from 'next/server'
export const dynamic = "force-static";
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  let page : any = searchParams.get('page');
  if(page==null) page=1;

  const res = await fetch(process.env.PATH_URL_BACKEND+`/api/posts?page=${page}`, {
   
    headers: {
      'Content-Type': 'application/json',
      //'API-Key': process.env.DATA_API_KEY,
    },
  })
  const result = await res.json()
  return NextResponse.json({ result })
}
 
export async function POST(request: Request,response: NextRequest) {
  const { title } = await request.json()
  return NextResponse.json({title})
}
 
```
Okay now we need to do it 
**+ app/post/[id]/pages.tsx**

```javascript
import Image from 'next/image'
async function getPost( id : number | string ) {
    console.log("->RUN 3",id);
  const res = await fetch(`http://127.0.0.1:8000/api/posts/${id}`);
  
  return res.json();
}
export default async function Page({ params }: { params: { id: number |  string } }) {
  console.log("->RUN 2",params);
 const data =  await getPost(params.id);
  return (
     <>
         <span>Title:{data.result.title}</span>
     </>
  )
}
 export async function generateStaticParams() {
  console.log("->RUN 1");
  const posts = await fetch('http://127.0.0.1:8000/api/posts').then((res) => res.json())
  return posts.data.map((post) => ({
   id: post.id.toString()
  }))
} 
```
Okay that's it, I'll run it, you can see the log

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34w3kjbkqzzqh3ac87t4.png)
+ First, it runs the function to fetch the api to get the post list data , it returns the correct post **id**

```javascript
generateStaticParams()
```
+ After running, it will send the post id parameter value to the Page component function for processing

```javascript
function Page({ params }: { params: { id: number |  string } })
```
+ In the Page function, it will read the parameters and call the api to get the returned information -> then display the data for the user to see.

```javascript
const data =  await getPost(params.id);
  return (
     <>
         <span>Title:{data.result.title}</span>
     </>
  )
```
Okay, complete
The article : [Example Of Using The GenerateStaticParams() In NextJs](https://hoanguyenit.com/example-of-using-the-generatestaticparams-in-nextjs-13.html)