Skip to lesson content

PROJECT 2 · LESSON 6 OF 18

Make catalog filters shareable

Keep search and sort in the URL so refresh and sharing preserve the view.

  • searchParams
  • GET forms
  • derived data

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Distinguish a resource path from a collection query

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

Why a GET form is enough

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.

Derive the visible list without changing the catalog

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The learner enters pen and chooses Price.

  2. The GET form requests /products?q=pen&sort=price.

  3. The page validates the query and derives a filtered, sorted array.

  4. The form, count and cards all render from that same query.

Manually compute a result

  1. For q=pen, Learning notebook and Desk lamp do not include pen. Pen set does.
  2. The resulting array has one record. Sorting it does not change its position.
  3. The count is 1 and the card price is ₹99.00.
  4. For an empty q and price sorting, the expected order is Pen set, Learning notebook, Desk lamp.

3. Build it, one file at a time

  1. Replace the catalog page below.
  2. Search for pen and sort by price. Inspect the address bar.
  3. Paste the resulting URL into a new tab.

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.

app/products/page.tsx

This page owns collection-level loading and renders one reusable card per resulting product.

app/products/page.tsx
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>}
    </>
  );
}

Read the code

  1. map creates ProductCard elements, each with one product prop and a stable id key. ProductCard does not fetch its own list.
  2. Await searchParams, normalize q to a bounded string and accept only supported sort values. A GET form writes those selections back into the URL.
  3. filter creates a new array; sort rearranges that copy. The count and empty message are derived from the same visible array used for cards.

4. Run it and check your result

  • The URL contains q and sort after submission.
  • A search with no matches displays useful feedback.

5. Predict, change and observe

Share /products?q=pen&sort=price with another browser window. Then remove q from the address.

Compare your prediction with the expected result

What you should observe

The first URL recreates the filtered view. Removing q displays all products sorted by price.

Why it happens

The search state is encoded in the URL rather than in one browser component instance.

6. Troubleshoot with evidence

A common mistake

Do not mutate your original products array with sort(). Here filter() creates a new array before sorting.

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.

Sorting gives a surprising numeric order.

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.

7. Practice and explain it back

Your independent task

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.

Why is searching a GET operation?

It retrieves a view without changing stored products. Its inputs can therefore be represented in a bookmarkable URL.

Does TypeScript make query input trustworthy?

No. A visitor controls the URL. Normalize and validate the runtime values before using them.