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
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 };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With