import { getUser } from "@utils/getUser";
export const preload = (id: string) => {
void getUser(id);
}
export default async function User({ id }: { id: string }) {
const result = await getUser(id);
// ...
}
import User, { preload } from '@components/User';
export default async function Page({
params: { id },
}: {
params: { id: string };
}) {
preload(id);
const condition = await fetchCondition();
return condition ? <User id={id} /> : null;
}
import Todo from './todo';
interface Todo {
id: number;
title: string;
completed: boolean;
}
async function getTodos() {
const res = await fetch('https://api.example.com/todos', {
cache: 'no-store',
});
const todos: Todo[] = await res.json();
return todos;
}
export default async function Page() {
const todos = await getTodos();
return (
<ul>
{todos.map((todo) => (
<Todo key={todo.id} {...todo} />
))}
</ul>
);
}
"use client";
import { useRouter } from 'next/navigation';
import { useState, useTransition } from 'react';
interface Todo {
id: number;
title: string;
completed: boolean;
}
export default function Todo(todo: Todo) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [isFetching, setIsFetching] = useState(false);
// 데이터 변경여부 확인
const isMutating = isFetching || isPending;
async function handleChange() {
setIsFetching(true);
// 데이터 패칭
await fetch(`https://api.example.com/todo/${todo.id}`, {
method: 'PUT',
body: JSON.stringify({ completed: !todo.completed }),
});
setIsFetching(false);
startTransition(() => {
// 서버에서 데이터를 새로 가져와 정보를 변경, 이 때 state는 유지됨
router.refresh();
});
}
return (
<li style={{ opacity: !isMutating ? 1 : 0.7 }}>
<input
type="checkbox"
checked={todo.completed}
onChange={handleChange}
disabled={isPending}
/>
{todo.title}
</li>
);
}
출처:
https://beta.nextjs.org/docs/data-fetching/caching
https://beta.nextjs.org/docs/data-fetching/revalidating
https://beta.nextjs.org/docs/data-fetching/mutating