본문으로 건너뛰기

서버에서 온 검사 메시지

Next.js 목차 서버 함수 레슨 29 / 47

목차

useActionState는 액션이 돌려준 값을 state로 들고 있는 리액트 훅입니다. 이 레슨은 서버 함수 createRecipe가 이름 칸이 비었을 때 검사 메시지를 돌려주게 하고, 그 메시지를 useActionState로 받아 폼 아래에 보입니다.

지금 createRecipe는 이름 칸이 비어도 저장하고, 칸 값이 글이 아니면 말없이 return합니다. 누른 사람은 무엇이 틀렸는지 모릅니다. 서버에서 검사한 결과를 폼으로 돌려줄 길이 있어야 합니다. 리액트 판 useActionState의 훅을 그대로 쓰고, 다른 것은 액션이 서버 함수라는 것뿐입니다.

1검사 결과를 돌려주는 서버 함수

createRecipe의 머리를 (prevState, formData)⁠로 바꾸고, 검사에 걸리면 메시지를 담은 객체를 돌려줍니다.

app/actions.ts
async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
…
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
…
  • useActionState로 부르는 액션은 첫 인자로 앞 state를, 둘째 인자로 폼 칸을 받습니다(Next.js 문서 Forms — 'receive a new prevState or initialState parameter as its first argument').
  • 이름 칸이 비었거나 빈칸뿐이면 메시지를 돌려주고 저장하지 않습니다. 분류 칸이 글이 아니면 분류를 골라 주세요입니다. 저장할 때는 title.trim()으로 앞뒤 빈칸을 지운 이름을 넘깁니다.
  • 저장하고 기억을 지운 뒤에는 { error: '' }를 돌려줍니다. 돌려준 값은 응답에 실려 브라우저로 가므로, 경계를 넘는 props처럼 글로 바꿀 수 있는 값이어야 합니다(Next.js 규칙 4).
  • 주석 // 2. 값 꺼내 검사하기가 서버 함수 차례의 둘째 걸음입니다. 이로써 1 ~ 4가 다 찼습니다.
app/actions.ts 전체
app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };

2useActionState로 메시지 보이기

state를 쓰는 폼은 클라이언트 컴포넌트여야 합니다. 새 파일 components/RecipeForm.tsx⁠로 폼을 옮깁니다.

components/RecipeForm.tsx
'use client';
…
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
…
    <form action={formAction}>
…
      <p>{state.error}</p>
  • 둘째 인자 { error: '' }가 첫 state입니다. state는 서버 함수가 마지막에 돌려준 값이고, 폼의 action에는 감싼 함수 formAction을 넘깁니다.
  • isPending은 응답을 기다리는 동안 true입니다. '더하기' 단추의 disabled에 달아 두 번 눌리지 않게 합니다.
  • 분류 목록은 쪽이 props categories로 넘깁니다. lib/recipes.ts는 파일을 읽는 서버 쪽 코드라, 클라이언트 컴포넌트는 글 배열만 받습니다.

쪽 파일 app/recipes/new/page.tsx⁠는 폼 대신 RecipeForm을 그립니다. 폼과 함께 // 1. 주석도 RecipeForm으로 옮겨 갔습니다.

app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
…
  return (
    <RecipeForm
      categories={categories}
    />
  );
…
components/RecipeForm.tsx · app/recipes/new/page.tsx 전체
components/RecipeForm.tsx
'use client';

import {
  useActionState,
} from 'react';
import {
  createRecipe,
} from '@/app/actions';

function RecipeForm({
  categories,
}: {
  categories: string[];
}) {
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={formAction}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button
        disabled={isPending}
      >
        더하기
      </button>
      <p>{state.error}</p>
    </form>
  );
}

export default RecipeForm;
app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;

세 파일을 다 저장했으면(레시피 보관함 탭은 닫은 채) 차례대로 합니다.

  1. 새 탭의 주소 칸에 /recipes/new를 쳐서 폼을 엽니다.
  2. 같은 탭에서 이름 칸을 비운 채 '더하기'를 누릅니다. 폼 아래에 이름을 적어 주세요가 보이고, 칸은 비워집니다(리액트 규칙 4 — 액션이 끝나면 칸을 처음 글로 되돌림).
  3. 같은 탭에서 이름 김밥, 분 10을 넣고 '더하기'를 다시 누릅니다.

3에서 createRecipe가 받은 첫 인자 prevState는 무엇일까요? 서버 터미널의 └─ ƒ createRecipe(…) 줄에 인자가 찍힙니다. 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① { error: '' } — 첫 state 그대로
  • ② { error: '이름을 적어 주세요' } — 바로 앞에 돌려준 값
  • ③ 아무것도 — 서버 함수는 앞 일을 모른다
결과 보기

②입니다. 아래는 1절 그대로의 app/actions.ts, 2에서 본 화면, 3까지 마친 서버 터미널입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" enctype="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_1"><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;6016231e365e64992d2a36d88d0613171eb017161a&quot;,&quot;bound&quot;:&quot;$@1&quot;}"><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;&quot;}]"><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"><input placeholder="이름" name="title"><select name="category" aria-label="분류"><option selected="">한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"><button>더하기</button><p>이름을 적어 주세요</p></form></section><footer>바닥글</footer>
결과 화면
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 221ms
✓ Running next.config.ts took 1001ms
- Cache Components enabled
- Partial Prefetching enabled

더하기 쪽을 그림
 GET /recipes/new 200 in 141ms (next.js: 62ms, application-code: 79ms)
 POST /recipes/new 200 in 7ms (next.js: 0.7ms, application-code: 6ms)
  └─ ƒ createRecipe({"error":""}, {}) in 0ms app/actions.ts
더하기 쪽을 그림
 POST /recipes/new 200 in 14ms (next.js: 0.6ms, application-code: 13ms)
  └─ ƒ createRecipe({"error":"이름을 적어 주세요"}, {}) in 2ms app/actions.ts

첫 보내기의 └─ ƒ createRecipe(…) 줄은 createRecipe({"error":""}, {})⁠입니다. 첫 인자가 첫 state이고, 둘째 인자 FormData는 {}로 찍힙니다. 둘째 보내기 줄의 첫 인자는 {"error":"이름을 적어 주세요"}⁠입니다. 2에서 돌려준 값이 state가 되었고, 리액트가 그 state를 다음 부름의 첫 인자로 보냈습니다. 둘째 보내기는 검사를 지나 updateTag까지 가서, 그 앞에 더하기 쪽을 그림이 한 번 더 찍혔습니다.

해 보기 — JS를 끄고 빈 이름으로 보내기

서버 함수 해 보기처럼 명령 메뉴에서 Disable JavaScript를 고르고 /recipes/new를 새로 고칩니다. 이름 칸을 비운 채 '더하기'를 누르면 메시지가 보일까요? 고른 뒤 펼쳐 보세요.

  • ① 보이지 않는다 — state를 바꾸는 것은 브라우저 JS니까
  • ② 오류 쪽이 뜬다
  • ③ 보인다 — 서버가 메시지를 넣어 그린 HTML로 답한다
결과 보기

③입니다. 아래는 2절 그대로의 세 파일과, JS 없이 빈 이름으로 '더하기'를 누른 POST에 돌아온 HTML(다듬음)입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };
components/RecipeForm.tsx
'use client';

import {
  useActionState,
} from 'react';
import {
  createRecipe,
} from '@/app/actions';

function RecipeForm({
  categories,
}: {
  categories: string[];
}) {
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={formAction}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button
        disabled={isPending}
      >
        더하기
      </button>
      <p>{state.error}</p>
    </form>
  );
}

export default RecipeForm;
app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_1"/><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;60b6836485aab183f2ad4a4918f82c3bb32375c8f7&quot;,&quot;bound&quot;:&quot;$@1&quot;}"/><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;이름을 적어 주세요&quot;}]"/><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"/><input placeholder="이름" name="title"/><select name="category" aria-label="분류"><option>한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"/><button>더하기</button><p>이름을 적어 주세요</p></form></section><footer>바닥글</footer>
결과 화면

폼 아래에 <p>이름을 적어 주세요</p>가 들어 있습니다. 폼 맨 앞에는 숨은 칸이 넷 있습니다. 처음 받은 폼에서는 그 가운데 name="$ACTION_1:1" 칸의 값 [{"error":""}]이 첫 state입니다(페이지 소스 보기로 볼 수 있습니다). JS가 없으면 브라우저는 이 칸들을 이름 칸과 함께 POST로 보냅니다. 서버는 createRecipe를 부르고, 돌려받은 state로 쪽을 그린 HTML을 보냅니다. 위 HTML의 그 칸에는 새 state [{"error":"이름을 적어 주세요"}]⁠이 들어 있어, 다음 '더하기'에 함께 갑니다.

다 봤으면 같은 명령 메뉴에서 Enable JavaScript를 고릅니다.

해 보기 — 메시지 이름을 바꿔 빌드하기

검사 메시지의 이름을 error 대신 message로 바꿔 돌려주면 어떻게 될까요? 이름 칸이 빈 때만 { message: '이름을 적어 주세요' }⁠를 돌려주게 고치고 npm run build를 돌립니다. 고른 뒤 펼쳐 보세요.

  • ① 빌드는 지나가고, 빈 이름으로 보내면 메시지가 안 보인다
  • ② 타입 검사에서 멈춘다 — 돌려준 꼴이 첫 state의 꼴과 다르다
  • ③ 쪽을 그리다가 멈춘다
결과 보기

②입니다. 아래는 message로 고친 app/actions.ts, 1 ~ 2절 그대로의 두 파일, 빌드 터미널입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      message: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };
components/RecipeForm.tsx
'use client';

import {
  useActionState,
} from 'react';
import {
  createRecipe,
} from '@/app/actions';

function RecipeForm({
  categories,
}: {
  categories: string[];
}) {
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={formAction}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button
        disabled={isPending}
      >
        더하기
      </button>
      <p>{state.error}</p>
    </form>
  );
}

export default RecipeForm;
app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;
  Creating an optimized production build ...
✓ Compiled successfully in 1320ms
  Running TypeScript ...
components/RecipeForm.tsx(21,5): error TS2769: No overload matches this call.
  Overload 1 of 2, '(action: (state: { message: string; error?: undefined; } | { error: string; message?: undefined; }) => { message: string; error?: undefined; } | { error: string; message?: undefined; } | Promise<{ message: string; error?: undefined; } | { ...; }>, initialState: { ...; } | { ...; }, permalink?: string | undefined): [state: ...]', gave the following error.
    Argument of type '(prevState: { error: string; }, formData: FormData) => Promise<{ message: string; error?: undefined; } | { error: string; message?: undefined; }>' is not assignable to parameter of type '(state: { message: string; error?: undefined; } | { error: string; message?: undefined; }) => { message: string; error?: undefined; } | { error: string; message?: undefined; } | Promise<{ message: string; error?: undefined; } | { ...; }>'.
      Target signature provides too few arguments. Expected 2 or more, but got 1.
  Overload 2 of 2, '(action: (state: { message: string; error?: undefined; } | { error: string; message?: undefined; }, payload: FormData) => { message: string; error?: undefined; } | { error: string; message?: undefined; } | Promise<...>, initialState: { ...; } | { ...; }, permalink?: string | undefined): [state: ...]', gave the following error.
    Argument of type '(prevState: { error: string; }, formData: FormData) => Promise<{ message: string; error?: undefined; } | { error: string; message?: undefined; }>' is not assignable to parameter of type '(state: { message: string; error?: undefined; } | { error: string; message?: undefined; }, payload: FormData) => { message: string; error?: undefined; } | { error: string; message?: undefined; } | Promise<...>'.
      Types of parameters 'prevState' and 'state' are incompatible.
        Type '{ message: string; error?: undefined; } | { error: string; message?: undefined; }' is not assignable to type '{ error: string; }'.
          Type '{ message: string; error?: undefined; }' is not assignable to type '{ error: string; }'.
            Types of property 'error' are incompatible.
              Type 'undefined' is not assignable to type 'string'.
Failed to type check.
exit=1

빌드는 Running TypeScript ... 다음에 Failed to type check.⁠로 멈췄습니다. 오류 자리는 app/actions.ts가 아니라 RecipeForm.tsx의 21번째 줄, useActionState에 넘긴 createRecipe 자리입니다. 타입스크립트는 서버 함수가 돌려줄 수 있는 값 모두를 state의 타입으로 봅니다. 거기에 { message }가 섞여, 서버 함수 머리의 prevState: { error: string }⁠과 맞지 않게 되었습니다. 오류 글 끝에 prevState와 state의 타입이 맞지 않는다고 나옵니다.

다 봤으면 message를 error로 되돌려 저장합니다.

예제

이름 칸에 빈칸 세 개만 넣고 '더하기'를 누르면 저장될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 저장되지 않고 이름을 적어 주세요가 보인다
  • ② 저장된다 — 빈칸도 글이니까
  • ③ 오류 쪽이 뜬다
결과 보기

①입니다. 아래는 1 ~ 2절 그대로의 세 파일, 빈칸 셋을 넣어 보낸 뒤의 화면과 서버 터미널입니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };
components/RecipeForm.tsx
'use client';

import {
  useActionState,
} from 'react';
import {
  createRecipe,
} from '@/app/actions';

function RecipeForm({
  categories,
}: {
  categories: string[];
}) {
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={formAction}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button
        disabled={isPending}
      >
        더하기
      </button>
      <p>{state.error}</p>
    </form>
  );
}

export default RecipeForm;
app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" enctype="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_REF_1"><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;601436ef460ae195aad6376cf50ac9dfa83e939907&quot;,&quot;bound&quot;:&quot;$@1&quot;}"><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;&quot;}]"><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"><input placeholder="이름" name="title"><select name="category" aria-label="분류"><option selected="">한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"><button>더하기</button><p>이름을 적어 주세요</p></form></section><footer>바닥글</footer>
결과 화면
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 256ms
✓ Running next.config.ts took 1190ms
- Cache Components enabled
- Partial Prefetching enabled

더하기 쪽을 그림
 GET /recipes/new 200 in 161ms (next.js: 61ms, application-code: 101ms)
 POST /recipes/new 200 in 8ms (next.js: 0.7ms, application-code: 7ms)
  └─ ƒ createRecipe({"error":""}, {}) in 0ms app/actions.ts

title.trim()은 앞뒤 빈칸을 지운 글입니다. 빈칸 셋은 지우면 빈 글이라 검사에 걸렸습니다. 터미널에 폼을 연 때의 더하기 쪽을 그림 하나뿐인 것도 그래서입니다 — updateTag까지 가지 않아 쪽을 다시 그리지 않았습니다.

다 봤으면 data/recipes.json에서 2절에 더한 김밥을 지워 씨앗 넷으로 되돌립니다. 바나나 팬케이크의 닫는 } 뒤 쉼표부터 맨 끝 ] 앞까지 지우면 됩니다. 해 보기와 예제는 검사에 걸려 더한 것이 없습니다. 되돌린 뒤 개발 서버를 Ctrl+C로 끄고 npm run dev로 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: useActionState로 부르는 서버 함수도 formData 하나만 받는다.

맞는 규칙: 첫 인자는 앞 state, 폼 칸은 둘째 인자입니다. 머리를 (formData)로 둔 채 useActionState에 넘기면 formData 자리에 state가 들어옵니다.

틀린 생각: 검사 메시지는 돌려준 값이니 함수나 클래스 객체도 돌려줄 수 있다.

맞는 규칙: 돌려준 값은 응답에 실려 브라우저로 갑니다. 글 · 수 · 배열 · 평범한 객체처럼 글로 바꿀 수 있는 값만 돌려줍니다(Next.js 규칙 4).

틀린 생각: 리액트 판처럼 검사는 브라우저에서 하면 된다.

맞는 규칙: 이 검사는 서버 함수 안에서 돕니다. 브라우저의 칸 검사는 사용자가 끄거나 건너뛸 수 있습니다. 그래도 지켜야 할 검사는 서버 함수 안에 둡니다(서버 함수는 공개 입구).

확인 문제

문제 1. useActionState에 넘긴 둘째 인자 { error: '' }는 무엇일까요?

  • ① 첫 state — 아직 아무것도 돌려받지 않았을 때의 값
  • ② 서버 함수가 늘 돌려줄 값
  • ③ 폼 칸의 처음 값
정답

①입니다. 처음 그릴 때 state가 이 값이고, 보낸 뒤에는 서버 함수가 돌려준 값으로 바뀝니다.

  • ② 돌려줄 값은 서버 함수가 그때그때 정합니다.
  • ③ 칸의 처음 값은 칸의 defaultValue가 정합니다.

문제 2. 이름 칸을 비운 채 두 번 연달아 '더하기'를 눌렀습니다. 둘째 부름에서 createRecipe의 prevState는 무엇일까요?

  • ① { error: '' }
  • ② { error: '이름을 적어 주세요' }
  • ③ 빈 FormData
정답

②입니다. 첫 부름이 돌려준 값이 state가 되었고, 둘째 부름에 첫 인자로 갑니다.

  • ① 첫 state는 첫 부름에만 갑니다.
  • ③ FormData는 둘째 인자 formData입니다.

문제 3. JS를 끈 브라우저에서 빈 이름으로 보낸 폼에도 메시지가 보이는 까닭은 무엇일까요?

  • ① 브라우저가 메시지를 기억해 두었다가 보여서
  • ② isPending이 true라서
  • ③ 서버가 돌려받은 state로 쪽을 그린 HTML을 보내서
정답

③입니다. 첫 state는 숨은 칸으로 폼과 함께 가고, 서버가 그 state로 서버 함수를 부른 뒤 쪽을 다시 그려 보냅니다.

  • ① JS가 없으면 브라우저는 state를 다루지 않습니다.
  • ② isPending은 JS가 도는 브라우저에서 응답을 기다리는 동안의 값입니다.
이 레슨에서 바꾼 파일

app/actions.ts — 머리 (prevState, formData) · 검사 메시지를 돌려줌

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  await addRecipe({
    title: title.trim(),
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
  // 4. 기억 지우기
  updateTag('recipes');
  return { error: '' };
}

export { createRecipe };

components/RecipeForm.tsx — 새 파일 · useActionState로 메시지 보이기

components/RecipeForm.tsx
'use client';

import {
  useActionState,
} from 'react';
import {
  createRecipe,
} from '@/app/actions';

function RecipeForm({
  categories,
}: {
  categories: string[];
}) {
  // 1. 폼에 서버 함수 달기
  const [
    state,
    formAction,
    isPending,
  ] = useActionState(
    createRecipe,
    { error: '' },
  );
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={formAction}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button
        disabled={isPending}
      >
        더하기
      </button>
      <p>{state.error}</p>
    </form>
  );
}

export default RecipeForm;

app/recipes/new/page.tsx — 폼 대신 RecipeForm

app/recipes/new/page.tsx
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로