Add id also in dynamic URLs like in stack overflows URLs

Viewed 184

I had some alert components when each clicked; it will get redirected to a page

 <div className="question11">
            {data.map((itm) => (
              <Link
                key={itm._id}
                href={{
                  pathname: "/[itm]",
                  query: { id: itm._id },
                }}
                as={`/${encodeURIComponent(
                  itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
                    / /g,
                    "-"
                  )
                )}`}
              >
                <Alert className="question13">{itm.Name}</Alert>
              </Link>
            ))}
          </div>

The redirected page has a URL in the following pattern http://localhost:3000/itm.Name. Example: http://localhost:3000/spiderman-no-way-home-release-date-in-india. I am passing itm._id for accessing the corresponding data on the redirected page

export async function getServerSideProps(context) {
  var id1 = context.query.id;

  // console.log(context.query.id);
  const queryRequest = fetch("https://askover.wixten.com/questone/" + id1).then(
    async (res) => await res.json()
  );

When I click on alert components, I can pass the itm._id, and the page is redirected properly. The issue occurs when I manually enter the URL in the browser.The issue here is not getting the itm._id from the alert component. The answer that I came up with here is to create an API to access the API by passing the itm.Name, but that will require deconstructing the itm.Name to its original form, and itm.Name might not be unique every time is there another method by which I can access itm._id itself also, if I can use the URL in http://localhost:3000/itm._id/itm.Name this format also, I think it will be okay just as StackOverflow does it.

1 Answers

When you refresh the page you will lose the context, even if you use some store(local, session, etc) that will not work for the user visiting your app for the first time.

One thing always remains is URL, neither storage nor context. To solve this kind of issue, what you can do is pass the id and slug parameters to the URL and read whenever requires.

Check more details here

Next.js Directory

  • pages

    • index.js
    • [id]
      • [slug].js

The URL will look something like this: https://localhost:3000/123/my-post-slug , Slug is optional, It'll help for SEO purposes.

[slug].js

const Component = (props) => (
  <div>
    <h1>{props.title}</h1>
    <p>{props.content}</p>
  </div>
);


export async function getServerSideProps(context) {
  const id = context.params.id;
  const data = fetch(`https://askover.wixten.com/questone/${id}`).then((res) => await res.json());
  return {
    props: data,
  }
}
Related