I'm wondering if anybody can point me in the right direction. I'm following the dynamic routes documentation on Next JS site - https://nextjs.org/docs/routing/dynamic-routes
Currently I'm rendering all products on the products
page. I'm using getServersideProps
to make the API call. Here is the products page:
import Link from "next/link";
const Products = ({ data }) => {
const products = data;
return (
<>
{products.map(({ id, name, seo: { description } }) => (
<div className="product" key={id}>
<h2>{name}</h2>
<p>{description}</p>
<Link href={`/products/${permalink}`}>
<a>View</a>
</Link>
</div>
))}
</>
);
};
export async function getServerSideProps() {
const headers = {
"X-Authorization": process.env.CHEC_API_KEY,
Accept: "application/json",
"Content-Type": "application/json",
};
const res = await fetch("https://api.chec.io/v1/products", {
method: "GET",
headers: headers,
});
const data = await res.json();
if (!data) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: data, // will be passed to the page component as props
};
}
export default Products;
In the Link I am using the permalink to direct people to a single product
<Link href={`/products/${permalink}`}>
<a>View</a>
</Link>
This is set up as products/[name].js
in the structure, with index.js
being the all products page.
Now on my single product page, [name].js
I would like to run another getServersideProps
to call the API and get the product - but I want to use the product id
however I'd only like to display the permalink/slug
in the URL.
Here is the [name].js
page:
import { useRouter } from "next/router";
const Product = () => {
const router = useRouter();
console.log(router);
return <p></p>;
};
export default Product;
Of course this is just logging out the Object with what I can access. The query shows [name]: "product-name", which is great - I could now make a call for all products and filter the product the that matches this slug but I want to use the product id
instead. Commerce.js has an request where I can request
a single product just by using its id
. How would I go about this?
Thanks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…