Open ShotaroHirose59 opened 6 months ago
URL に検索クエリとフィルターを直接含めることで、追加のクライアント側ロジックを必要とせずに、ユーザーの行動を追跡することが容易になります
useStateで状態管理しなくて良いのでかなり好き 検索パラメータを状態として扱う設計
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で受け取る設計にすることで再利用可能なコンポーネントになっている
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()}
/>
page.jsはparams
とsearchParams
をpropsとして受け取れる
参考: https://nextjs.org/docs/app/api-reference/file-conventions/page
searchParams
はSC、useSearchParams()
フックはCCで使う
やっぱ検索とページネーションが必要なデータフェッチ関数にはqueryとcurrentPageを持たせるよな
const invoices = await fetchFilteredInvoices(query, currentPage);
デバウンスは、関数が起動できる速度を制限するプログラミング手法です。この例では、ユーザーが入力をやめたときにのみデータベースにクエリを実行する必要があります。
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
searchParams
,usePathname
, anduseRouter
.