'Return two values from getStaticPaths
I'm using getStaticPaths to create a product page within NextJS. I get my products from wooCommerce, problem is:
I want to use "permalink" for my NextJS route URL, but I need product.id to get data for that particular product that is being rendered.
My code looks something like this:
export async function getStaticPaths() {
const res = await fetch('https://.../products/')
const products = await res.json()
const paths = products.map((product) => ({
params: { permalink: product.slug, id: product.id},
}))
return { paths, fallback: false }
}
export async function getStaticProps({params}) {
console.log(params);
const res = await fetch(`https://.../products/${params.id}`)
const productsData = await res.json()
return { props: { productsData } }
}
I'm trying to pass id in params, but NextJS only expects variables that is in JS filename (in this case, [permalink].js) so ID is not being passed down to getStaticProps, and I need ID to get product data since API doesn't work with permalink.
Is there any way I can pass another variable (ID in this case) from getStaticPaths to getStaticProps?
Solution 1:[1]
export async function getStaticPaths() {
const res = await fetch('https://.../products/')
const products = await res.json()
let paths = []
for (const product of products){
paths.push({params: {permalink: product.slug }, id: product.your_map_id})
}
return { paths, fallback: false }
}
Solution 2:[2]
You need to create a nested dynamic route. page/[permalink]/[id].js
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 | illia chill |
Solution 2 | MarkosTh09 |