Since Day 2, pages have loaded data with await. Today is about doing that
well: fast, with something on screen while it loads, and with a plan for when
it fails.
Two queriesNext.js · 4 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>Study Hub</header>
{children}
</body>
</html>
);
}
import { getProfile, getTopics } from "@/lib/db.js";
// Load fresh data on every request, rather than once when the site is built.
export const dynamic = "force-dynamic";
export default async function HomePage() {
const started = Date.now();
const profile = await getProfile();
const topics = await getTopics();
console.log(`Loaded in ${Date.now() - started} ms`);
return (
<main>
<h1>Welcome back, {profile.name}</h1>
<p>Streak: {profile.streak} days</p>
<ul>
{topics.map((topic) => <li key={topic}>{topic}</li>)}
</ul>
</main>
);
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
color: #1c2430;
}
header,
main,
footer {
max-width: 36rem;
margin: 0 auto;
padding: 0.75rem 1rem;
}
header {
border-bottom: 1px solid #d6dde6;
}
nav {
display: flex;
gap: 1rem;
}
a {
color: #06617f;
}
h1 {
margin: 0.5rem 0;
}
.muted {
color: #5b6876;
}
.card {
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
// A pretend database. Each query takes a while, like a real one over the network.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function getProfile() {
console.log("query: profile");
await wait(500);
return { name: "Ada", streak: 4 };
}
export async function getTopics() {
console.log("query: topics");
await wait(500);
return ["Routing", "Server components", "Dynamic routes"];
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
lib/db.js pretends to be a database: each query takes half a second. The page
needs two, a profile and a list of topics:
await pauses until the answer arrives. The second query doesn't start
until the first has finished, so the console says Loaded in about 1000 ms:
twice as long as either query.
The queries don't depend on each other. The topics don't need the profile.
Calling both functions starts both queries straight away. Promise.all waits
for all of them and gives back their answers in the same order. When both
succeed, the wait is roughly the slowest query, rather than their sum.
If either rejects, Promise.all rejects; it doesn't cancel the other query.
Use this when both results are needed and a failure should fail this part of
the page. The next lessons handle the loading and error UI.
Use one after the other only when the second really needs the first's answer:
for example, loading a user, then that user's topics by their id.
About that first line
JavaScript
export const dynamic = "force-dynamic";
In next dev and in these labs, every page is built fresh for each visit. A
production build of real Next.js can build a page once, in advance, when
nothing about the visit changes it, and serve that copy to everyone. Then the
queries would run once, when the site is built, and nobody would see a page
load. This line asks for a fresh page every time, as a live dashboard needs.
Day 7 comes back to this.
Exercise
Make it faster
Change the page so both queries run at the same time. Check the console: what
does Loaded in say now?
Your working spaceNext.js · 4 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>Study Hub</header>
{children}
</body>
</html>
);
}
import { getProfile, getTopics } from "@/lib/db.js";
// Load fresh data on every request, rather than once when the site is built.
export const dynamic = "force-dynamic";
export default async function HomePage() {
const started = Date.now();
const profile = await getProfile();
const topics = await getTopics();
console.log(`Loaded in ${Date.now() - started} ms`);
return (
<main>
<h1>Welcome back, {profile.name}</h1>
<p>Streak: {profile.streak} days</p>
<ul>
{topics.map((topic) => <li key={topic}>{topic}</li>)}
</ul>
</main>
);
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
color: #1c2430;
}
header,
main,
footer {
max-width: 36rem;
margin: 0 auto;
padding: 0.75rem 1rem;
}
header {
border-bottom: 1px solid #d6dde6;
}
nav {
display: flex;
gap: 1rem;
}
a {
color: #06617f;
}
h1 {
margin: 0.5rem 0;
}
.muted {
color: #5b6876;
}
.card {
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
// A pretend database. Each query takes a while, like a real one over the network.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function getProfile() {
console.log("query: profile");
await wait(500);
return { name: "Ada", streak: 4 };
}
export async function getTopics() {
console.log("query: topics");
await wait(500);
return ["Routing", "Server components", "Dynamic routes"];
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Independent requests can start together. Keep the association between each result and the variable that needs it.
Hint 2: a first step
Replace the two await lines with one Promise.all, and destructure the
answers.