Skip to content

Step 3 - Data fetching in Next

Course: NextJS (Server side) - chapter 3

Ref - https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating

💡 You can do the same thing as the last slide in Next.js, but then you lose the benefits of server side rendering

You should fetch the user details on the server side and pre-render the page before returning it to the user.

  1. Initialise an empty next project
npx create-next-app@latest
  1. Install axios
npm i axios
  1. Clean up page.tsx, global.css
  2. In the root page.tsx, write a function to fetch the users details
async function getUserDetails() {
const response = await axios.get("https://week-13-offline.kirattechnologies.workers.dev/api/v1/user/details")
return response.data;
}
  1. Convert the default export to be an async function (yes, nextjs now supports async components)
import axios from "axios";
async function getUserDetails() {
const response = await axios.get("https://week-13-offline.kirattechnologies.workers.dev/api/v1/user/details")
return response.data;
}
export default async function Home() {
const userData = await getUserDetails();
return (
<div>
{userData.email}
{userData.name}
</div>
);
}
  1. Check the network tab, make sure there is no waterfalling

  2. Prettify the UI

import axios from "axios";
async function getUserDetails() {
const response = await axios.get("https://week-13-offline.kirattechnologies.workers.dev/api/v1/user/details")
return response.data;
}
export default async function Home() {
const userData = await getUserDetails();
return (
<div className="flex flex-col justify-center h-screen">
<div className="flex justify-center">
<div className="border p-8 rounded">
<div>
Name: {userData?.name}
</div>
{userData?.email}
</div>
</div>
</div>
);
}

Good question to ask at this point - Where is the loader ?

Do we even need a loader ?