Home > Blockchain >  passing id through Link to getServerSideProps :next js
passing id through Link to getServerSideProps :next js

Time:05-24

i have some alert compoents. from each of the compoent i want to pass the itm._id

and recive it in [itm].jsx in the same folder in the [itm].jsx i want to use it in the getServerSideProps funtion to fetch data

index.jsx

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

flowing is the getServerSideProps function the error now i am getting is that

Server Error FetchError: invalid json response body at https://askover.wixten.com/questone/[object Object] reason: Unexpected token < in JSON at position 0

i think the error is id is recived as object how do i fix this

[itm].jsx

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

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

  const responses = await Promise.all([queryRequest, answerRequest]);
  const [posts, answerPosts] = await Promise.all(responses);

  return {
    props: {
      posts,
      answerPosts,
    },
  };
}

enter image description here

enter image description here

enter image description here

CodePudding user response:

Try this: In Link Tag pass query as

<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>

And in getserversideprops you can access it like this

export async function getServerSideProps(context) {
  console.log(contex.params.id)  //If doesn't work use context.query.id
}

CodePudding user response:

You have to receive itm from query like below. query itself a object. Inside object your path variable exists as your dynamic filename. You are fetching data by object. you have to fetch data by itm alias as id1.

export async function getServerSideProps({ query }) {
  var {itm: id1} = query;
  ...

  return {
    props: {
      posts,
      answerPosts,
    },
  };
}

CodePudding user response:

If you see the documentation for getServerSideProps you'll see the parameter is called context - this is an object, not the id you're expecting.

https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props

export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

Quote:

The context parameter is an object containing the following keys:

  • req: The HTTP IncomingMessage object.
  • res: The HTTP response object.
  • query: An object representing the query string.

(others removed)

Therefore your query params will be in context.query.

Try this:

export async function getServerSideProps(context) {
  const query = context.query
  console.log(query?.itm);
  // ^  
}

You named the query param itm (as the file is called [itm].tsx) - so context.query.itm should give you the value you need. Check in the console before you add the URL.

CodePudding user response:

I think the issue is that you're not destructuring the query from the parameters of getServerSideProps The error tells you you are making a request to /[object object] which means your id is not a string it's the entire props object of the getServerSideProps function.

export async function getServerSideProps(query)

replace it with

export async function getServerSideProps({query})

  • Related