简体   繁体   中英

how to generate dynamic pages without knowing the static paths on NextJS?

I want to route my users to a page where they can get discounts based on their citizenship id numbers. I will use their id number to determine the amount of discount they get. I can use their id to determine Location, Age, Gender etc.

They can route to mywebsite.com/megadiscount and fill in their id number in a box and find out how much discount they can get. But now the issue is that I also want them to be able to get a link to mywebsite.com/megadiscount/[id number] to find out how much discount they can get.

So with NextJS I know I can create megadiscount/index.js and megadiscount/[id].js to capture the id from the url.

The problem is that on megadiscount/[id].js I have to specify with a getStaticPaths the id pages I will be generating but the problem is that I have no knowledge what these id's will be.

My megadiscount/[id].js file looks like this

const Page = ({discount}) => {
  return (
    <>
      <h1>You get a discount of : {discount}%</h1>
    </>
  )
}


export async function getStaticPaths() {

  return {
    paths: [], // I don't know what these will be
    fallback: false,
  };
}

export async function getStaticProps(context) {
  const { slug = "" } = context.params;
  const discount = fetchDiscountFromServer(slug)
  return {
    props: {
      discount
    },
  };
}

export default Page;
export default function Page({ discount }) {
  return (
    <>
      <h1>You get a discount of : {discount}%</h1>
    </>
  );
}

export async function getStaticProps({ params: { id } }) {
  //Featch your discount based on id
  const discount = await fetchDiscountFromServer(id);
  return {
    props: { discount },
  };
}
export async function getStaticPaths() {
  return {
    paths: [],
    fallback: "blocking",
  };
}

NextJS offers fallback:"blocking" for cases like this. Check out the docs

But You should think about SSR in this case, In my opinion. This will generate a static page for every user which is fine but If you frequently change your discount You have to set a low revalidate:1 value but still that wont be realtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM