In Next.js App Router, you cannot use await directly inside a Client Component (i.e., components with 'use client'). The pattern you posted is only valid in a Server Component, where data fetching is done on the server and the result is rendered as HTML. However, Server Components cannot handle client-side events like button clicks to create a new book and then update the UI with the new list.
To achieve the behavior you want—fetching the updated list of books after creating a new one—you should use a Client Component and fetch data on the client side. The recommended approach is to use a data-fetching library like SWR or React Query, which handles revalidation and cache updates for you. Here’s how you can do it with SWR:
'use client'
import useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then(res => res.json())
export default function Page() {
const { data: books, mutate } = useSWR('/api/books', fetcher)
const createBook = async (name) => {
await fetch('/api/books', {
method: 'POST',
body: JSON.stringify({ name }),
headers: { 'Content-Type': 'application/json' },
})
mutate()
}
if (!books) return <div>Loading...</div>
return (
<div>
{/* Your form or button to create a book, calling createBook */}
<ul>
{books.map(book => (
<li key={book.id}>{book.name}</li>
))}
</ul>
</div>
)
}
Here, mutate() will re-fetch the books after a new one is created, updating the UI automatically. This is the recommended pattern for client-side data updates in Next.js Client Components see SWR example.