The address changes but the input appears empty.
Likely cause: The form did not initialize its value from the query.
Check and correct: Use the normalized q as defaultValue and the normalized sort for the select.
PROJECT 2 · LESSON 6 OF 18
Keep search and sort in the URL so refresh and sharing preserve the view.
Continue from lesson 5: Build individual product pages. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
Filters should survive refreshing a page and sharing its address. Storing search only in a component’s state would make a copied URL lose the chosen view. Here the URL becomes the source of truth for the catalog view.
A product slug identifies a resource. Query parameters describe a view of a collection. /products?q=pen&sort=price can be bookmarked and shared.
The server reads query parameters, derives a filtered list, and renders it. A GET form is sufficient; this feature does not need a useEffect or client-side fetch.
/products/pen-set identifies one product. /products?q=pen&sort=price still identifies the catalog, with instructions for how to display it. q and sort are query parameters. They do not create additional folders or routes.
The page receives searchParams as a Promise. A query value can be missing, a string, or an array when a parameter repeats. The example accepts q only when it is a string and limits its length. It accepts only the known sort value price; every other input falls back to name.
The form action is the destination URL and method=get makes the browser encode named controls into the query string. The input name q and select name sort become the parameter names. The page does not need a client-side event handler to make a search request.
defaultValue initializes each control from the URL so the visible form agrees with the current result. Submitting Apply causes another render for the selected query. This introductory form can perform a normal navigation; it does not promise instant filtering on every keystroke.
filter creates a new array containing products whose lowercased name includes the lowercased search text. sort then rearranges that new array. Sorting the original imported array directly would mutate a shared source and make later behavior harder to reason about.
For price, a.price - b.price orders numeric values from low to high. For name, localeCompare orders text. visible.length is derived from the same array used to render cards, keeping the result count consistent. An empty array is a successful search with no matches, not a server error.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The learner enters pen and chooses Price.
The GET form requests /products?q=pen&sort=price.
The page validates the query and derives a filtered, sorted array.
The form, count and cards all render from that same query.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This page owns collection-level loading and renders one reusable card per resulting product.
import { products } from "@/lib/products";
import ProductCard from "@/components/product-card";
type Query = { q?: string | string[]; sort?: string | string[] };
export default async function ProductsPage({
searchParams,
}: {
searchParams: Promise<Query>;
}) {
const query = await searchParams;
const q = typeof query.q === "string" ? query.q.trim().slice(0, 100) : "";
const sort = query.sort === "price" ? "price" : "name";
const visible = products
.filter((p) => p.name.toLowerCase().includes(q.toLowerCase()))
.sort((a, b) =>
sort === "price" ? a.price - b.price : a.name.localeCompare(b.name),
);
return (
<>
<h1>Products</h1>
<form action="/products" method="get">
<label>
Search <input name="q" defaultValue={q} maxLength={100} />
</label>
<label>
Sort{" "}
<select name="sort" defaultValue={sort}>
<option value="name">Name</option>
<option value="price">Price: low to high</option>
</select>
</label>
<button>Apply</button>
</form>
<p>{visible.length} products</p>
<div className="grid">
{visible.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
{visible.length === 0 && <p>No matches. Try another search.</p>}
</>
);
}
Share /products?q=pen&sort=price with another browser window. Then remove q from the address.
The first URL recreates the filtered view. Removing q displays all products sorted by price.
The search state is encoded in the URL rather than in one browser component instance.
Do not mutate your original products array with sort(). Here filter() creates a new array before sorting.
Likely cause: The form did not initialize its value from the query.
Check and correct: Use the normalized q as defaultValue and the normalized sort for the select.
Likely cause: Default array sorting or string comparison was used for prices.
Check and correct: Use the numeric comparator a.price - b.price on the filtered array.
Add a category dropdown and preserve it in the query string.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
It retrieves a view without changing stored products. Its inputs can therefore be represented in a bookmarkable URL.
No. A visitor controls the URL. Normalize and validate the runtime values before using them.