0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js実務でよく使う3つ:Zod / モックデータ / 'use client' をわかりやすく解説

0
Posted at

モック用仮データ(SEED)

モックって何?
→APIがまだ無い/呼びたくない時に使う「仮の固定データ」

画面だけ先に作りたい!

  • バックエンド未完成
  • ローカル確認用

でめちゃくちゃ使う。

シンプルなモックデータ

// User 型
type User = {
  id: number;
  name: string;
  display_name: string;
};

// 仮データ(モック)
export const SEED: User[] = [
  {
    id: 1,
    name: '山田',
    display_name: '山田さん',
  },
  {
    id: 2,
    name: '佐藤',
    display_name: '佐藤さん',
  },
];

使い方(例:mapで表示)

{SEED.map((user) => (
  <li key={user.id}>{user.display_name}</li>
))}

APIレスポンスと同じ形にしておくのがコツ
あとで差し替えが楽。

'use client':クライアントコンポーネント宣言

これは何?
Next.js(App Router)では、

デフォルト=サーバーで動く
でもこれを使いたい時は…

  • useState
  • useEffect
  • クリックイベント
  • フォーム操作

ブラウザ側で動かす必要がある
その宣言が 'use client'。

最小サンプル

'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}

ポイント

ファイルの一番上に書く(必須)
書かないと

useState is not supported in Server Components

みたいなエラー出る

3つをまとめた使い方例

'use client';

import { z } from 'zod';

// Zod
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  display_name: z.string(),
});
type User = z.infer<typeof UserSchema>;

// モック
const SEED: User[] = [
  { id: 1, name: '山田', display_name: '山田さん' },
  { id: 2, name: '佐藤', display_name: '佐藤さん' },
];

export default function UserList() {
  return (
    <ul>
      {SEED.map((user) => (
        <li key={user.id}>{user.display_name}</li>
      ))}
    </ul>
  );
}
  • zod → 安全装置
  • モック → 開発スピード用の仮物
  • 'use client' → 「これはブラウザ用だよ」の合図
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?