ShotaroHirose59 / nextjs-dashboard

Learn Next.js
https://nextjs-dashboard-dun-pi-28.vercel.app
0 stars 0 forks source link

Chapter11 Adding Search and Pagination #17

Open ShotaroHirose59 opened 6 months ago

ShotaroHirose59 commented 6 months ago

In the previous chapter, you improved your dashboard's initial loading performance with streaming. Now let's move on to the /invoices page, and learn how to add search and pagination! https://nextjs.org/learn/dashboard-app/adding-search-and-pagination

topics

ShotaroHirose59 commented 6 months ago

なぜ URL 検索パラメータを使用するのか?

URL に検索クエリとフィルターを直接含めることで、追加のクライアント側ロジックを必要とせずに、ユーザーの行動を追跡することが容易になります

useStateで状態管理しなくて良いのでかなり好き 検索パラメータを状態として扱う設計

ShotaroHirose59 commented 6 months ago

Searchコンポーネント

export default function Search({ placeholder }: { placeholder: string }) {
  return (
    <div className="relative flex flex-1 flex-shrink-0">
      <label htmlFor="search" className="sr-only">
        Search
      </label>
      <input
        className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
        placeholder={placeholder}
      />
      <MagnifyingGlassIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
    </div>
  );
}

placeholderをpropsで受け取る設計にすることで再利用可能なコンポーネントになっている

ShotaroHirose59 commented 6 months ago
const searchParams = useSearchParams(); // 現在の URL のクエリ文字列を読み取ることができる
const pathname = usePathname(); // 現在のURLのpathを取得 /dashboard/invoices
const { replace } = useRouter(); // 現在のURLのPathを書き換えるための関数
replace(`${pathname}?${params.toString()}`);

ブックマークを想定すると、URLを入力内容を同期するためにdefaultValueを設定しておく必要がありそうだ

<input
        className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
        placeholder={placeholder}
        onChange={(e) => {
          handleSearch(e.target.value);
        }}
        defaultValue={searchParams.get('query')?.toString()}
      />
ShotaroHirose59 commented 6 months ago

page.jsはparamssearchParamsをpropsとして受け取れる

スクリーンショット 2024-03-18 0 37 27

参考: https://nextjs.org/docs/app/api-reference/file-conventions/page

searchParamsはSC、useSearchParams()フックはCCで使う

ShotaroHirose59 commented 6 months ago

やっぱ検索とページネーションが必要なデータフェッチ関数にはqueryとcurrentPageを持たせるよな

const invoices = await fetchFilteredInvoices(query, currentPage);
ShotaroHirose59 commented 6 months ago

Best practice: Debouncing

デバウンスは、関数が起動できる速度を制限するプログラミング手法です。この例では、ユーザーが入力をやめたときにのみデータベースにクエリを実行する必要があります。