📖

【nuqs】NextJs & nqus 【#4 CreateLoader】

に公開

【#4 CreateLoader】

YouTube: https://youtu.be/bZmXzi0b8qM
https://youtu.be/bZmXzi0b8qM

今回はサーバーコンポーネントの「page.tsx」で
paramsを取得する方法について解説します。

https://nuqs.dev/docs/server-side

src/components/search-params.tsx
import {
  createLoader,
  parseAsInteger,
  parseAsString,
  parseAsStringEnum,
} from "nuqs/server";

export enum Colors {
  Blue = "blue",
  Red = "red",
  Green = "green",
  Yellow = "yellow",
}

export const filtersParams = {
  search: parseAsString.withDefault("").withOptions({ clearOnDefault: true }),
  page: parseAsInteger.withDefault(0).withOptions({ clearOnDefault: true }),
  color: parseAsStringEnum(Object.values(Colors)),
};

export const loadSearchParams = createLoader(filtersParams);
src/app/page.tsx
import type { SearchParams } from "nuqs/server";

import { SearchFilters } from "@/components/search-filters";
import { loadSearchParams } from "@/components/search-params";

interface Props {
  searchParams: Promise<SearchParams>;
}

export default async function Home({ searchParams }: Props) {
  const qStrings = await loadSearchParams(searchParams);
  // void queryClient.prefetchQuery(
  //   trpc.getMany.queryOptions({
  //     ...qStrings,
  //   })
  // )

  return (
    <div className="w-full h-full flex flex-col justify-center items-center p-10 gap-y-3">
      <h1 className="text-3xl font-black">Search Filters</h1>
      <SearchFilters />
      {JSON.stringify(qStrings, null, 2)}
    </div>
  );
}

Discussion