Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 536
Droidbane Avatar asked Sep 17 '25 03:09

Droidbane


1 Answers

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 };
    }
}
like image 186
Anish Antony Avatar answered Sep 19 '25 18:09

Anish Antony