Home > OS >  NextJS - How do I make an api fetch with the use of a router id? Also how do I render it as html?
NextJS - How do I make an api fetch with the use of a router id? Also how do I render it as html?

Time:09-10

Hello I'm writing code in NextJS and am currently trying to do a user page that displays user specific information from an API. I want to load the id query from the address bar and use that to make an API call.

The API looks like this; /Users/{id}

Furthermore I need some help to load that data to the rendered page.

In the address bar the link looks like this: http://localhost:3000/userPage?id=2

So this is what my code look like on page userPage:


import { useRouter } from "next/router";

function GetQuery(){
  const router = useRouter();
  const id = router.query.id;
  return id; 
}


export const getServerSidePros = async (id) =>  {
  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  return {
    props: { users: data },
  };
};


const UserPage = (users) => {
  return (
    <div>
      <h1>Hello</h1>
      <h1>{users.name}</h1>
    </div>
  );
}

I don't think the id from the adress bar is being picked up. I get Hello to render but nothing else.

Also the GetQuery function is never read.

CodePudding user response:

export const getServerSidePros = async (context) =>  {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  return {
    props: { users: data },
  };
};


const UserPage = ({users}) => {
  return (
    <div>
      <h1>Hello</h1>
      <h1>{users.name}</h1>
    </div>
  );
}

You can use context.query inside the getServerSidePros to access the query params.

  • Related