'How to get slug value in getStaticProps to call api with parameter as slug

Page content:

import { useRouter } from "next/router";
    
export default function Gunluk({ data }) {
    let router = useRouter()
    
    const { slug } = router.query;
    return slug;
}

And show on the page 60d6180ea9284106a4fd8441 (https://.../gunluk/60d6180ea9284106a4fd8441 id in URL)

So I can get the ID but I don't know how to pass it to API.

export async function getStaticProps(context) {
    const res = await fetch(`http://localhost:3000/api/books-i-have`)
    const data = await res.json()
    
    if (!data) {
        return {
            notFound: true,
        }
    }
    
    return {
        props: { data }, // will be passed to the page component as props
    }
}

Normally I use this but it didn't work in slug. I tried both other methods but failed (https://nextjs.org/docs/basic-features/data-fetching).

In short, how do you connect to the API from the Slug page?

File directory:

    pages/
        gunluk/
            [...slug].js
            index.js


Solution 1:[1]

You can get the slug value in getStaticProps and use it to call api based on slug

export async function getStaticPaths() {
    const idList = await fetchAllIds();
    const paths = [];
    idList.forEach((id) => { paths.push(`/gunluk/${id}`) })
    return { paths, fallback: true };
}

export async function getStaticProps({ params }) {
    const { slug } = params;

    try {
        const data = await fetchGunluk(slug);
        return data ? { props: { data } } : { notFound: true };
    } catch (error) {
        console.error(error);
        return { notFound: true };
    }
}

Solution 2:[2]

i did this, i have a file name pages/course/[course_slug].js in next js project

  const router = useRouter();
  const slug = router.query.course_slug;
  console.log(slug); //slug value

Solution 3:[3]

I believe what you're looking for is the getStaticPaths

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zenci Musa
Solution 2 Abhi Raj
Solution 3 Noriller