Return two values from getStaticPaths

1.5k Views Asked by At

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?

2

There are 2 best solutions below

1
On
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 }
}
0
On

You need to create a nested dynamic route. page/[permalink]/[id].js