In nextJS How to get parameter in getStaticPaths function

25 Views Asked by At

I have /[locale]/suscripcion/[brand]/[model]/[version] page

and when I build the project I am getting

Collecting page data ..Error: A required parameter (brand) was not provided as a string in getStaticPaths for /[locale]/suscripcion/[brand]/[model]/[version]

I know I need to provide params inside getStaticPaths function but I don't know how.

[brand]/[model]/[version] coming from the URL

1

There are 1 best solutions below

3
Hamude Shahin On

Try this:

// This function is used to generate paths at build time
export async function getStaticPaths() {
  // Fetch the data that will be used to generate paths
  // For example, fetch a list of brands, models, and versions

  // Assume brands, models, and versions are arrays obtained from your data source
  const brands = ['brand1', 'brand2'];
  const models = ['model1', 'model2'];
  const versions = ['version1', 'version2'];

  // Generate all possible combinations of paths
  const paths = brands.flatMap(brand =>
    models.flatMap(model =>
      versions.map(version => ({
        params: {
          locale: 'your_locale', // You may replace this with the actual locale or fetch it dynamically
          brand,
          model,
          version,
        },
      }))
    )
  );

  // Return the paths to Next.js
  return {
    paths,
    fallback: false, // Set to true if you want to enable fallback for paths not generated at build time
  };
}

// This function is used to fetch data for each specific path
export async function getStaticProps({ params }) {
  // Fetch data for the specific path using params
  // For example, fetch data for the specified brand, model, and version

  // Your data fetching logic

  // Return the data to the component
  return {
    props: {
      // Your data
    },
  };
}

// Your page component
function YourPage({ /* your props */ }) {
  // Your component logic

  return (
    // Your JSX
  );
}

export default YourPage;