Unverified Commit 5f4238d9 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

docs: `useFormState` (#55564)

This PR shows how to use a new React hook `useFormState` in the context
of the [Forms and
Mutations](https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations)
docs. It also updates the forms example (`next-forms`) to show the
recommended patterns for loading / error states.

Related: https://github.com/vercel/next.js/pull/55399
---
Co-authored-by: 's avatarJohn Pham <johnphammail@gmail.com>
parent c923257c
...@@ -64,31 +64,64 @@ export default function PostList({ posts }) { ...@@ -64,31 +64,64 @@ export default function PostList({ posts }) {
You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to determine if a link is active. For example, to add a class to the active link, you can check if the current `pathname` matches the `href` of the link: You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to determine if a link is active. For example, to add a class to the active link, you can check if the current `pathname` matches the `href` of the link:
```jsx filename="app/ui/Navigation.js" ```tsx filename="app/components/links.tsx"
'use client' 'use client'
import { usePathname } from 'next/navigation' import { usePathname } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
export function Navigation({ navLinks }) { export function Links() {
const pathname = usePathname() const pathname = usePathname()
return ( return (
<> <nav>
{navLinks.map((link) => { <ul>
const isActive = pathname === link.href <li>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
</li>
<li>
<Link
className={`link ${pathname === '/about' ? 'active' : ''}`}
href="/"
>
About
</Link>
</li>
</ul>
</nav>
)
}
```
```jsx filename="app/components/links.jsx"
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return ( return (
<nav>
<ul>
<li>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
</li>
<li>
<Link <Link
className={isActive ? 'text-blue' : 'text-black'} className={`link ${pathname === '/about' ? 'active' : ''}`}
href={link.href} href="/"
key={link.name}
> >
{link.name} About
</Link> </Link>
) </li>
})} </ul>
</> </nav>
) )
} }
``` ```
......
...@@ -360,14 +360,16 @@ export default async function submit(formData) { ...@@ -360,14 +360,16 @@ export default async function submit(formData) {
<AppOnly> <AppOnly>
Use the `useFormStatus` hook to show a loading state when a form is submitting on the server: Use the `useFormStatus` hook to show a loading state when a form is submitting on the server. The `useFormStatus` hook can only be used as a child of a `form` element using a Server Action.
```tsx filename="app/page.tsx" switcher For example, the following submit button:
```tsx filename="app/submit-button.tsx" switcher
'use client' 'use client'
import { experimental_useFormStatus as useFormStatus } from 'react-dom' import { experimental_useFormStatus as useFormStatus } from 'react-dom'
function SubmitButton() { export function SubmitButton() {
const { pending } = useFormStatus() const { pending } = useFormStatus()
return ( return (
...@@ -376,12 +378,12 @@ function SubmitButton() { ...@@ -376,12 +378,12 @@ function SubmitButton() {
} }
``` ```
```jsx filename="app/page.jsx" switcher ```jsx filename="app/submit-button.jsx" switcher
'use client' 'use client'
import { experimental_useFormStatus as useFormStatus } from 'react-dom' import { experimental_useFormStatus as useFormStatus } from 'react-dom'
function SubmitButton() { export function SubmitButton() {
const { pending } = useFormStatus() const { pending } = useFormStatus()
return ( return (
...@@ -390,9 +392,40 @@ function SubmitButton() { ...@@ -390,9 +392,40 @@ function SubmitButton() {
} }
``` ```
> **Good to know:** `<SubmitButton />` can then be used in a form with a Server Action:
>
> - Displaying loading or error states currently requires using Client Components. We are exploring options for server-side functions to retrieve these values as we move forward in stability for Server Actions. ```tsx filename="app/page.tsx" switcher
import { SubmitButton } from '@/app/submit-button'
export default async function Home() {
return (
<form action={...}>
<input type="text" name="field-name" />
<SubmitButton />
</form>
)
}
```
```jsx filename="app/page.jsx" switcher
import { SubmitButton } from '@/app/submit-button'
export default async function Home() {
return (
<form action={...}>
<input type="text" name="field-name" />
<SubmitButton />
</form>
)
}
```
<details>
<summary>Examples</summary>
- [Form with Loading & Error States](https://github.com/vercel/next.js/tree/canary/examples/next-forms)
</details>
</AppOnly> </AppOnly>
...@@ -484,18 +517,17 @@ export default function Page() { ...@@ -484,18 +517,17 @@ export default function Page() {
<AppOnly> <AppOnly>
Server Actions can also return [serializable objects](https://developer.mozilla.org/docs/Glossary/Serialization). For example, your Server Action might handle errors from creating a new item, returning either a success or error message: Server Actions can also return [serializable objects](https://developer.mozilla.org/docs/Glossary/Serialization). For example, your Server Action might handle errors from creating a new item:
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
'use server' 'use server'
export async function create(formData: FormData) { export async function create(prevState: any, formData: FormData) {
try { try {
await createItem(formData.get('item')) await createItem(formData.get('todo'))
revalidatePath('/') return revalidatePath('/')
return { message: 'Success!' }
} catch (e) { } catch (e) {
return { message: 'There was an error.' } return { message: 'Failed to create' }
} }
} }
``` ```
...@@ -503,70 +535,98 @@ export async function create(formData: FormData) { ...@@ -503,70 +535,98 @@ export async function create(formData: FormData) {
```js filename="app/actions.js" switcher ```js filename="app/actions.js" switcher
'use server' 'use server'
export async function create(formData) { export async function createTodo(prevState, formData) {
try { try {
await createItem(formData.get('item')) await createItem(formData.get('todo'))
revalidatePath('/') return revalidatePath('/')
return { message: 'Success!' }
} catch (e) { } catch (e) {
return { message: 'There was an error.' } return { message: 'Failed to create' }
} }
} }
``` ```
Then, from a Client Component, you can read this value and save it to state, allowing the component to display the result of the Server Action to the viewer. Then, from a Client Component, you can read this value and display an error message.
```tsx filename="app/page.tsx" switcher ```tsx filename="app/add-form.tsx" switcher
'use client' 'use client'
import { create } from './actions' import { experimental_useFormState as useFormState } from 'react-dom'
import { useState } from 'react' import { experimental_useFormStatus as useFormStatus } from 'react-dom'
import { createTodo } from '@/app/actions'
export default function Page() { const initialState = {
const [message, setMessage] = useState<string>('') message: null,
}
async function onCreate(formData: FormData) { function SubmitButton() {
const res = await create(formData) const { pending } = useFormStatus()
setMessage(res.message)
} return (
<button type="submit" aria-disabled={pending}>
Add
</button>
)
}
export function AddForm() {
const [state, formAction] = useFormState(createTodo, initialState)
return ( return (
<form action={onCreate}> <form action={formAction}>
<input type="text" name="item" /> <label htmlFor="todo">Enter Task</label>
<button type="submit">Add</button> <input type="text" id="todo" name="todo" required />
<p>{message}</p> <SubmitButton />
<p aria-live="polite" className="sr-only">
{state?.message}
</p>
</form> </form>
) )
} }
``` ```
```jsx filename="app/page.jsx" switcher ```jsx filename="app/add-form.jsx" switcher
'use client' 'use client'
import { create } from './actions' import { experimental_useFormState as useFormState } from 'react-dom'
import { useState } from 'react' import { experimental_useFormStatus as useFormStatus } from 'react-dom'
import { createTodo } from '@/app/actions'
export default function Page() { const initialState = {
const [message, setMessage] = useState('') message: null,
}
async function onCreate(formData) { function SubmitButton() {
const res = await create(formData) const { pending } = useFormStatus()
setMessage(res.message)
}
return ( return (
<form action={onCreate}> <button type="submit" aria-disabled={pending}>
<input type="text" name="item" /> Add
<button type="submit">Add</button> </button>
<p>{message}</p> )
}
export function AddForm() {
const [state, formAction] = useFormState(createTodo, initialState)
return (
<form action={formAction}>
<label htmlFor="todo">Enter Task</label>
<input type="text" id="todo" name="todo" required />
<SubmitButton />
<p aria-live="polite" className="sr-only">
{state?.message}
</p>
</form> </form>
) )
} }
``` ```
> **Good to know:** <details>
> <summary>Examples</summary>
> - Displaying loading or error states currently requires using Client Components. We are exploring options for server-side functions to retrieve these values as we move forward in stability for Server Actions.
- [Form with Loading & Error States](https://github.com/vercel/next.js/tree/canary/examples/next-forms)
</details>
</AppOnly> </AppOnly>
......
...@@ -9,7 +9,7 @@ import { z } from 'zod' ...@@ -9,7 +9,7 @@ import { z } from 'zod'
// text TEXT NOT NULL // text TEXT NOT NULL
// ); // );
export async function createTodo(formData: FormData) { export async function createTodo(prevState: any, formData: FormData) {
const schema = z.object({ const schema = z.object({
todo: z.string().nonempty(), todo: z.string().nonempty(),
}) })
...@@ -24,14 +24,13 @@ export async function createTodo(formData: FormData) { ...@@ -24,14 +24,13 @@ export async function createTodo(formData: FormData) {
` `
revalidatePath('/') revalidatePath('/')
return { message: `Added todo ${data.todo}` }
return { message: 'Saved successfully' }
} catch (e) { } catch (e) {
return { message: 'Failed to create todo' } return { message: 'Failed to create todo' }
} }
} }
export async function deleteTodo(formData: FormData) { export async function deleteTodo(prevState: any, formData: FormData) {
const schema = z.object({ const schema = z.object({
id: z.string().nonempty(), id: z.string().nonempty(),
}) })
...@@ -39,10 +38,15 @@ export async function deleteTodo(formData: FormData) { ...@@ -39,10 +38,15 @@ export async function deleteTodo(formData: FormData) {
id: formData.get('id'), id: formData.get('id'),
}) })
await sql` try {
DELETE FROM todos await sql`
WHERE id = ${data.id}; DELETE FROM todos
` WHERE id = ${data.id};
`
revalidatePath('/') revalidatePath('/')
return { message: `Deleted todo ${data.todo}` }
} catch (e) {
return { message: 'Failed to delete todo' }
}
} }
'use client'
import { experimental_useFormState as useFormState } from 'react-dom'
import { experimental_useFormStatus as useFormStatus } from 'react-dom'
import { createTodo } from '@/app/actions'
const initialState = {
message: null,
}
function SubmitButton() {
const { pending } = useFormStatus()
return (
<button type="submit" aria-disabled={pending}>
Add
</button>
)
}
export function AddForm() {
const [state, formAction] = useFormState(createTodo, initialState)
return (
<form action={formAction}>
<label htmlFor="todo">Enter Task</label>
<input type="text" id="todo" name="todo" required />
<SubmitButton />
<p aria-live="polite" className="sr-only" role="status">
{state?.message}
</p>
</form>
)
}
'use client'
import { createTodo } from '@/app/actions'
import { useState } from 'react'
export default function Form() {
const [message, setMessage] = useState('')
async function onCreateTodo(formData: FormData) {
const res = await createTodo(formData)
setMessage(res.message)
}
return (
<form action={onCreateTodo}>
<input type="text" name="todo" />
<button type="submit">Add</button>
<p>{message}</p>
</form>
)
}
'use client'
import { experimental_useFormState as useFormState } from 'react-dom'
import { experimental_useFormStatus as useFormStatus } from 'react-dom'
import { deleteTodo } from '@/app/actions'
const initialState = {
message: null,
}
function DeleteButton() {
const { pending } = useFormStatus()
return (
<button type="submit" aria-disabled={pending}>
Delete
</button>
)
}
export function DeleteForm({ id }: { id: number }) {
const [state, formAction] = useFormState(deleteTodo, initialState)
return (
<form action={formAction}>
<input type="hidden" name="id" value={id} />
<DeleteButton />
<p aria-live="polite" className="sr-only" role="status">
{state?.message}
</p>
</form>
)
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #f5f5f5;
padding: 20px;
}
label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
input[type='text'] {
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
width: 100%;
box-sizing: border-box;
margin-bottom: 10px;
border-radius: 4px;
outline-offset: 4px;
}
button {
background-color: black;
border-radius: 4px;
color: white;
padding: 10px 24px;
border: none;
cursor: pointer;
width: 100%;
font-size: 16px;
outline-offset: 4px;
}
button:hover {
opacity: 0.8;
}
button[aria-disabled='true'] {
opacity: 0.5;
cursor: not-allowed;
}
ul {
padding: 0;
margin: auto;
}
li {
background: #f9f9f9;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
import './global.css'
export const metadata = { export const metadata = {
title: 'Next.js Forms Example', title: 'Next.js Forms Example',
description: 'Example application with forms and Postgres.', description: 'Example application with forms and Postgres.',
......
import { sql } from '@vercel/postgres' import { sql } from '@vercel/postgres'
import { createTodo, deleteTodo } from '@/app/actions' import { AddForm } from '@/app/add-form'
import { DeleteForm } from '@/app/delete-form'
export const runtime = 'edge' export const runtime = 'edge'
export const preferredRegion = 'home' export const preferredRegion = 'home'
...@@ -9,22 +10,17 @@ export default async function Home() { ...@@ -9,22 +10,17 @@ export default async function Home() {
const { rows: todos } = data const { rows: todos } = data
return ( return (
<div> <main>
<form action={createTodo}> <h1 className="sr-only">Todos</h1>
<input type="text" name="todo" /> <AddForm />
<button type="submit">Add</button>
</form>
<ul> <ul>
{todos.map((todo) => ( {todos.map((todo) => (
<li key={todo.id}> <li key={todo.id}>
{todo.text} {todo.text}
<form action={deleteTodo}> <DeleteForm id={todo.id} />
<input type="hidden" name="id" value={todo.id} />
<button type="submit">Delete</button>
</form>
</li> </li>
))} ))}
</ul> </ul>
</div> </main>
) )
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment