본문으로 건너뛰기

즐겨찾기

Next.js 목차 레시피 보관함 Next.js 판 레슨 43 / 47

목차

즐겨찾기는 카드의 별을 눌러 그 레시피를 서버 파일에 표시해 두는 일입니다. 이 레슨은 별 단추 FavoriteButton을 useOptimistic과 서버 함수 toggleFavorite로 고쳐, 누르면 별이 바로 바뀌고 저장이 끝나면 그대로 확정되게 합니다.

지금 별은 useState로 그 브라우저 화면에서만 바뀝니다. 파일에는 쓰지 않아, 새로 고치면 파일의 값으로 돌아갑니다. 리액트 판은 dispatch로 목록 state를 바꾸고 그 브라우저의 저장소에 써서 기다릴 일이 없었습니다(레시피 보관함 — 목록 · 검색 · 더하기). Next.js 판은 서버 파일에 쓰는 서버 함수를 기다려야 합니다. 그동안 보일 별은 useOptimistic — 기다리지 않고 먼저 보이기의 낙관 값으로 둡니다.

1별을 저장하는 서버 함수

먼저 파일의 별을 바꾸는 함수를 lib/recipes.ts 맨 끝에 더합니다. addRecipe처럼 파일을 읽어 검사한 목록을 만들고, id가 같은 레시피만 favorite를 바꿔 통째로 다시 씁니다.

lib/recipes.ts
…
// 파일을 읽어 그 레시피의 별만 바꿈
export const updateFavorite =
  async (
    id: string,
    favorite: boolean,
  ) => {
    …
    const next = list.map((r) =>
      r.id === id
        ? { ...r, favorite }
        : r,
    );
    …

서버 함수는 app/actions.ts의 createRecipe 아래에 둡니다. 주석 번호는 createRecipe와 같은 틀('서버 함수로 바꾸고 다시 읽기')의 하위 목표입니다. 맨 위 import에 updateFavorite를, 맨 끝 export에 toggleFavorite를 더합니다.

app/actions.ts
…
  // 2. 값 꺼내 검사하기
  if (
    typeof id !== 'string' ||
    typeof favorite !==
      'boolean'
  ) {
    throw new Error('잘못된 값');
  }
  // 3. 저장하기
  …
  • 2. 서버 함수는 누구나 부를 수 있는 입구입니다(규칙 8). 내 별 단추는 늘 글과 참거짓을 보내지만, 다른 길로 온 요청은 무엇이든 보낼 수 있습니다. 별 단추에는 메시지 칸이 없으니 틀린 값이면 던집니다.
  • 3 · 4. updateFavorite로 저장하고 updateTag('recipes')로 기억을 지웁니다. 목록 · 자세히 · 통계가 모두 'recipes' 이름표의 기억을 쓰니, 이 한 줄로 셋 다 다음에 파일을 새로 읽습니다.

toggleFavorite는 폼 칸이 아니라 인자 둘 (id, favorite)를 받습니다. 별 단추가 자바스크립트로 직접 부르기 때문입니다(2절).

2별은 낙관 값으로

별 단추 components/FavoriteButton.tsx⁠의 useState를 useOptimistic으로 바꾸고, 누르면 서버 함수를 부릅니다. 파일 맨 위의 'use client'는 그대로입니다. 주석 1 '경계 표시와 import'는 'use client' 위에, 4 '별 그리기'는 return 위에 답니다.

components/FavoriteButton.tsx
…
  // 2. 별을 낙관 값으로 두기
  const [starred, setStarred] =
    useOptimistic(
      recipe.favorite,
    );
  // 3. 누르면 서버 함수로 저장
  async function handleStar() {
    setStarred(!starred);
    await toggleFavorite(
      recipe.id,
      !starred,
    );
  }
  …

단추는 <form action={handleStar}>⁠로 감쌉니다. 폼의 action에 함수를 달면 리액트가 그 함수를 액션으로 돌립니다. 그래서 그 안에서 부른 setStarred가 낙관 set이 됩니다.

components/FavoriteButton.tsx 전체
components/FavoriteButton.tsx
// 1. 경계 표시와 import
'use client';

import {
  useOptimistic,
} from 'react';
import {
  toggleFavorite,
} from '@/app/actions';
import type {
  Recipe,
} from '@/lib/recipes';

function FavoriteButton({
  recipe,
}: {
  recipe: Recipe;
}) {
  // 2. 별을 낙관 값으로 두기
  const [starred, setStarred] =
    useOptimistic(
      recipe.favorite,
    );
  // 3. 누르면 서버 함수로 저장
  async function handleStar() {
    setStarred(!starred);
    await toggleFavorite(
      recipe.id,
      !starred,
    );
  }
  // 4. 별 그리기
  return (
    <form action={handleStar}>
      <button>
        {starred ? '★' : '☆'}
      </button>
    </form>
  );
}

export default FavoriteButton;
  • 누르자마자. setStarred(!starred)는 저장을 기다리지 않고 바로 ★를 그립니다. 저장에 2초가 걸리게 해 두고 누르면, 별은 누르자마자 ★이고 파일은 그 2초 동안 false입니다.
  • 저장이 끝나면. updateTag를 부른 서버 함수의 응답에는 새로 그린 쪽이 같이 옵니다. 액션이 끝나면 starred는 첫 인자 recipe.favorite로 돌아가는데, 그 값이 이제 true라 별은 ★ 그대로입니다.
  • 던지면. 액션이 끝나 낙관 값이 사라지고, 오류는 가장 가까운 오류 경계로 갑니다. 이 앱에서는 app/global-error.tsx의 '앱을 못 그렸습니다'입니다(개발 서버는 그 위에 오류 판을 먼저 띄웁니다 — 오류 화면). '다시'를 누르면 파일 값 그대로 ☆가 섭니다.

카드 RecipeCard는 서버 컴포넌트 그대로입니다. 브라우저에서 도는 것은 경계 안의 별 단추뿐입니다.

예제

고친 세 파일 가운데 lib/recipes.ts · app/actions.ts를 모으면 아래와 같습니다. 별 단추 파일 전체는 2절 접기에 있습니다. 목록에서 토마토 파스타의 ☆를 누르고, 목록을 새로 고칩니다. 별은 무엇일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

lib/recipes.ts 전체
lib/recipes.ts
import {
  readFile,
  writeFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };

// 기억한 목록이 아니라 파일을 읽음
export const addRecipe = async (
  input: {
    title: string;
    category: string;
    minutes: number;
  },
) => {
  const text = await readFile(
    'data/recipes.json',
    'utf8',
  );
  const data: unknown =
    JSON.parse(text);
  const list: Recipe[] =
    Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  const recipe: Recipe = {
    id: crypto.randomUUID(),
    ...input,
    ingredients: [],
    favorite: false,
  };
  list.push(recipe);
  await writeFile(
    'data/recipes.json',
    JSON.stringify(
      list, null, 2,
    ),
  );
  return recipe;
};

// 파일을 읽어 그 레시피의 별만 바꿈
export const updateFavorite =
  async (
    id: string,
    favorite: boolean,
  ) => {
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    const list: Recipe[] =
      Array.isArray(data)
        ? data.filter(isRecipe)
        : [];
    const next = list.map((r) =>
      r.id === id
        ? { ...r, favorite }
        : r,
    );
    await writeFile(
      'data/recipes.json',
      JSON.stringify(
        next, null, 2,
      ),
    );
  };
app/actions.ts 전체
app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
  categories,
  updateFavorite,
} 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 (title.length > 30) {
    return {
      error: '이름은 30자까지',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  if (
    !categories.includes(
      category,
    )
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  const minutes = Number(
    formData.get('minutes'),
  );
  if (
    minutes < 1 ||
    !Number.isInteger(minutes)
  ) {
    return {
      error: '분은 1 이상 정수로',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes,
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

async function toggleFavorite(
  id: string,
  favorite: boolean,
) {
  // 2. 값 꺼내 검사하기
  if (
    typeof id !== 'string' ||
    typeof favorite !==
      'boolean'
  ) {
    throw new Error('잘못된 값');
  }
  // 3. 저장하기
  await updateFavorite(
    id,
    favorite,
  );
  // 4. 기억 지우기
  updateTag('recipes');
}

export {
  createRecipe,
  toggleFavorite,
};
  • ① ☆ — 별은 브라우저 화면에서만 바뀌었다
  • ② ★ — 누를 때 서버 함수가 파일에 썼다
  • ③ ★ — 브라우저가 별을 기억해 두었다
결과 보기

②입니다. 아래는 2절 그대로의 별 단추 파일, 목록에서 첫 ☆(토마토 파스타)를 누른 뒤 화면과 개발 서버 터미널, 목록을 새로 연 화면입니다.

components/FavoriteButton.tsx
// 1. 경계 표시와 import
'use client';

import {
  useOptimistic,
} from 'react';
import {
  toggleFavorite,
} from '@/app/actions';
import type {
  Recipe,
} from '@/lib/recipes';

function FavoriteButton({
  recipe,
}: {
  recipe: Recipe;
}) {
  // 2. 별을 낙관 값으로 두기
  const [starred, setStarred] =
    useOptimistic(
      recipe.favorite,
    );
  // 3. 누르면 서버 함수로 저장
  async function handleStar() {
    setStarred(!starred);
    await toggleFavorite(
      recipe.id,
      !starred,
    );
  }
  // 4. 별 그리기
  return (
    <form action={handleStar}>
      <button>
        {starred ? '★' : '☆'}
      </button>
    </form>
  );
}

export default FavoriteButton;
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<form action="/recipes">
<input name="q">
<button>찾기</button>
</form><a href="/recipes/new">새 레시피</a><a href="/recipes?sort=fastest">빠른 순</a>
<p><a href="/recipes">▸ 전체 </a><a href="/recipes?category=한식">한식 </a><a href="/recipes?category=양식">양식 </a><a href="/recipes?category=일식">일식 </a><a href="/recipes?category=중식">중식 </a><a href="/recipes?category=디저트">디저트 </a></p>
<ul>
  <li><a href="/recipes/r1">김치볶음밥</a><span>15분</span>
<form action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')">
<button>★</button>
</form></li>
  <li><a href="/recipes/r2">토마토 파스타</a><span>25분</span>
<form action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')">
<button>★</button>
</form></li>
  <li><a href="/recipes/r3">계란말이</a><span>10분</span>
<form action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')">
<button>☆</button>
</form></li>
  <li><a href="/recipes/r4">바나나 팬케이크</a><span>20분</span>
<form action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')">
<button>★</button>
</form></li>
</ul>
</section>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></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
- Environments: .env.local
✓ Ready in 205ms
✓ Running next.config.ts took 983ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 332ms (next.js: 93ms, application-code: 239ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음
 POST /recipes 200 in 21ms (next.js: 3ms, application-code: 18ms)
  └─ ƒ toggleFavorite("r2", true) in 2ms app/actions.ts
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<form action="/recipes">
<input name="q">
<button>찾기</button>
</form><a href="/recipes/new">새 레시피</a><a href="/recipes?sort=fastest">빠른 순</a>
<p><a href="/recipes">▸ 전체 </a><a href="/recipes?category=한식">한식 </a><a href="/recipes?category=양식">양식 </a><a href="/recipes?category=일식">일식 </a><a href="/recipes?category=중식">중식 </a><a href="/recipes?category=디저트">디저트 </a></p>
<ul>
  <li><a href="/recipes/r1">김치볶음밥</a><span>15분</span>
<form action="javascript:throw new Error('React form unexpectedly submitted.')">
<button>★</button>
</form></li>
  <li><a href="/recipes/r2">토마토 파스타</a><span>25분</span>
<form action="javascript:throw new Error('React form unexpectedly submitted.')">
<button>★</button>
</form></li>
  <li><a href="/recipes/r3">계란말이</a><span>10분</span>
<form action="javascript:throw new Error('React form unexpectedly submitted.')">
<button>☆</button>
</form></li>
  <li><a href="/recipes/r4">바나나 팬케이크</a><span>20분</span>
<form action="javascript:throw new Error('React form unexpectedly submitted.')">
<button>★</button>
</form></li>
</ul>
</section>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>
결과 화면

터미널의 POST /recipes 줄이 별 단추가 부른 서버 함수입니다. 그 아래 줄에 함수 이름과 인자 toggleFavorite("r2", true)⁠가 찍힙니다. POST 줄 위의 꼬리표 없는 레시피 파일 읽음은 기억을 지운 뒤 서버가 쪽을 새로 그리며 파일을 다시 읽은 줄입니다. 그렇게 새로 그린 쪽이 응답에 같이 옵니다. 새로 연 목록은 파일을 다시 읽어 그렸고, 토마토 파스타는 ★입니다. 리액트 판처럼 브라우저 저장소에 둔 것이 아니라, 다른 브라우저로 열어도 ★입니다. 별을 한 번 더 누르면 data/recipes.json의 favorite도 false로 되돌아갑니다.

다 봤으면 토마토 파스타의 별을 한 번 더 눌러 처음처럼 ☆로 되돌립니다.

자주 틀리는 곳

틀린 생각: 별 단추가 클라이언트 컴포넌트이니 카드 RecipeCard에도 'use client'를 단다.

맞는 규칙: 'use client' 파일이 import한 모듈은 모두 클라이언트로 끌려갑니다. 카드는 서버에서 그리고, 경계는 별 단추 파일에만 둡니다('use client' 경계).

틀린 생각: 누를 때 바뀔 별을 useState로 따로 들고, 저장이 끝나면 맞춘다.

맞는 규칙: useState는 첫 값만 props에서 받습니다. 서버가 새로 그린 recipe.favorite가 와도 따라가지 않습니다. useOptimistic은 액션이 끝나면 저절로 그때의 props 값으로 돌아옵니다(useOptimistic — 기다리지 않고 먼저 보이기 2절).

확인 문제

문제 1. useOptimistic(recipe.favorite)⁠이 돌려준 starred는 액션이 끝난 뒤 무엇을 보일까요?

  • ① 그때의 recipe.favorite
  • ② 마지막으로 낙관 set한 값
  • ③ 처음 그릴 때의 값
정답

①입니다. 낙관 값은 액션이 도는 동안만 보입니다. 끝나면 첫 인자로 돌아가고, 서버가 새로 그렸다면 그 새 값입니다(2절).

  • ② 낙관 set한 값은 액션이 끝나면 사라집니다.
  • ③ useOptimistic은 처음 값을 들고 있지 않습니다. 그때그때의 props를 봅니다.

문제 2. 이 레슨이 끝난 목록 쪽에서 클라이언트 컴포넌트는 어느 것일까요?

  • ① RecipeCard
  • ② RecipeList
  • ③ FavoriteButton
정답

③입니다. 목록 쪽 파일과 RecipeList · RecipeCard 가운데 'use client' 파일은 별 단추뿐입니다. 위의 탭 막대 TabBar는 루트 레이아웃이 그리는 클라이언트 컴포넌트입니다.

  • ① 카드는 서버 컴포넌트입니다. 별 단추를 자식으로 그릴 뿐입니다.
  • ② RecipeList는 await로 주소 값을 읽는 서버 컴포넌트입니다.

문제 3. 누군가 toggleFavorite를 불러 favorite 자리에 글 'true'를 보내면 어떻게 될까요?

  • ① 참으로 읽어 저장한다
  • ② 던진다 — 참거짓이 아니다
  • ③ 아무 일 없이 끝난다
정답

②입니다. 검사가 typeof favorite !== 'boolean'⁠을 보고 잘못된 값 오류를 던집니다. 파일은 바뀌지 않습니다(1절 하위 목표 2).

  • ① 글 'true'는 참거짓 true가 아닙니다. 검사를 지나지 못합니다.
  • ③ 검사에 걸리면 저장 줄까지 가지 않고 던집니다.
이 레슨에서 바꾼 파일

lib/recipes.ts — updateFavorite

lib/recipes.ts
import {
  readFile,
  writeFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };

// 기억한 목록이 아니라 파일을 읽음
export const addRecipe = async (
  input: {
    title: string;
    category: string;
    minutes: number;
  },
) => {
  const text = await readFile(
    'data/recipes.json',
    'utf8',
  );
  const data: unknown =
    JSON.parse(text);
  const list: Recipe[] =
    Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  const recipe: Recipe = {
    id: crypto.randomUUID(),
    ...input,
    ingredients: [],
    favorite: false,
  };
  list.push(recipe);
  await writeFile(
    'data/recipes.json',
    JSON.stringify(
      list, null, 2,
    ),
  );
  return recipe;
};

// 파일을 읽어 그 레시피의 별만 바꿈
export const updateFavorite =
  async (
    id: string,
    favorite: boolean,
  ) => {
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    const list: Recipe[] =
      Array.isArray(data)
        ? data.filter(isRecipe)
        : [];
    const next = list.map((r) =>
      r.id === id
        ? { ...r, favorite }
        : r,
    );
    await writeFile(
      'data/recipes.json',
      JSON.stringify(
        next, null, 2,
      ),
    );
  };

app/actions.ts — toggleFavorite

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
  categories,
  updateFavorite,
} 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 (title.length > 30) {
    return {
      error: '이름은 30자까지',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  if (
    !categories.includes(
      category,
    )
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  const minutes = Number(
    formData.get('minutes'),
  );
  if (
    minutes < 1 ||
    !Number.isInteger(minutes)
  ) {
    return {
      error: '분은 1 이상 정수로',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes,
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

async function toggleFavorite(
  id: string,
  favorite: boolean,
) {
  // 2. 값 꺼내 검사하기
  if (
    typeof id !== 'string' ||
    typeof favorite !==
      'boolean'
  ) {
    throw new Error('잘못된 값');
  }
  // 3. 저장하기
  await updateFavorite(
    id,
    favorite,
  );
  // 4. 기억 지우기
  updateTag('recipes');
}

export {
  createRecipe,
  toggleFavorite,
};

components/FavoriteButton.tsx — 낙관 별 · 서버 함수

components/FavoriteButton.tsx
// 1. 경계 표시와 import
'use client';

import {
  useOptimistic,
} from 'react';
import {
  toggleFavorite,
} from '@/app/actions';
import type {
  Recipe,
} from '@/lib/recipes';

function FavoriteButton({
  recipe,
}: {
  recipe: Recipe;
}) {
  // 2. 별을 낙관 값으로 두기
  const [starred, setStarred] =
    useOptimistic(
      recipe.favorite,
    );
  // 3. 누르면 서버 함수로 저장
  async function handleStar() {
    setStarred(!starred);
    await toggleFavorite(
      recipe.id,
      !starred,
    );
  }
  // 4. 별 그리기
  return (
    <form action={handleStar}>
      <button>
        {starred ? '★' : '☆'}
      </button>
    </form>
  );
}

export default FavoriteButton;

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

Next.js 목차로