Skip to content

Commit 2177e28

Browse files
smith558aurorascharffclaude
authored
Fix Server Function examples for Actions, forms, and useActionState (#8538)
* Fix Server Functions documentation examples * Fix code snippet highlights Corrected the index of 'submitAction' in the code snippet. * Clarify wording * Update section titles for clarity * Polish Server Functions examples: consistent headings, reset wording, transition comment - Convert the remaining two Usage headings to gerund form to match the rest of the page and react.dev convention (anchors unchanged) - Reset wording: "succeeds" + "the form's uncontrolled fields" (aligns with #8512) - Comment the startTransition-after-await; bump CodeStep line accordingly Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Polish Server Functions examples * Fix Server Functions code highlight --------- Co-authored-by: Aurora Scharff <aurora.sofie@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 6b0a30d commit 2177e28

1 file changed

Lines changed: 78 additions & 35 deletions

File tree

‎src/content/reference/rsc/server-functions.md‎

Lines changed: 78 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,23 @@ Server Functions can be created in Server Components and passed as props to Clie
3434

3535
## Usage {/*usage*/}
3636

37-
### Creating a Server Function from a Server Component {/*creating-a-server-function-from-a-server-component*/}
37+
### Creating a Server Function in a Server Component {/*creating-a-server-function-from-a-server-component*/}
3838

3939
Server Components can define Server Functions with the `"use server"` directive:
4040

4141
```js [[2, 7, "'use server'"], [1, 5, "createNoteAction"], [1, 12, "createNoteAction"]]
4242
// Server Component
4343
import Button from './Button';
4444

45-
function EmptyNote () {
45+
function EmptyNote() {
4646
async function createNoteAction() {
4747
// Server Function
4848
'use server';
4949

5050
await db.notes.create();
5151
}
5252

53-
return <Button onClick={createNoteAction}/>;
53+
return <Button onClick={createNoteAction} />;
5454
}
5555
```
5656

@@ -62,59 +62,64 @@ When React renders the `EmptyNote` Server Component, it will create a reference
6262
export default function Button({onClick}) {
6363
console.log(onClick);
6464
// {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'}
65-
return <button onClick={() => onClick()}>Create Empty Note</button>
65+
return <button onClick={() => onClick()}>Create Empty Note</button>;
6666
}
6767
```
6868

6969
For more, see the docs for [`"use server"`](/reference/rsc/use-server).
7070

71-
72-
### Importing Server Functions from Client Components {/*importing-server-functions-from-client-components*/}
71+
### Importing a Server Function into a Client Component {/*importing-server-functions-from-client-components*/}
7372

7473
Client Components can import Server Functions from files that use the `"use server"` directive:
7574

76-
```js [[1, 3, "createNote"]]
75+
```js [[1, 4, "createNote"]]
76+
// actions.js
7777
"use server";
7878

7979
export async function createNote() {
8080
await db.notes.create();
8181
}
82-
8382
```
8483

8584
When the bundler builds the `EmptyNote` Client Component, it will create a reference to the `createNote` function in the bundle. When the `button` is clicked, React will send a request to the server to execute the `createNote` function using the reference provided:
8685

87-
```js [[1, 2, "createNote"], [1, 5, "createNote"], [1, 7, "createNote"]]
86+
```js [[1, 4, "createNote"], [1, 7, "createNote"], [1, 9, "createNote"]]
87+
// EmptyNote.js
8888
"use client";
89+
8990
import {createNote} from './actions';
9091

9192
function EmptyNote() {
9293
console.log(createNote);
9394
// {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNote'}
94-
<button onClick={() => createNote()} />
95+
return <button onClick={() => createNote()}>Create Empty Note</button>;
9596
}
9697
```
9798

9899
For more, see the docs for [`"use server"`](/reference/rsc/use-server).
99100

100-
### Server Functions with Actions {/*server-functions-with-actions*/}
101+
### Calling a Server Function from an Action {/*server-functions-with-actions*/}
101102

102103
Server Functions can be called from Actions on the client:
103104

104-
```js [[1, 3, "updateName"]]
105+
```js [[1, 4, "updateName"]]
106+
// actions.js
105107
"use server";
106108

107109
export async function updateName(name) {
108110
if (!name) {
109111
return {error: 'Name is required'};
110112
}
111113
await db.users.updateName(name);
114+
return {error: null};
112115
}
113116
```
114117

115-
```js [[1, 3, "updateName"], [1, 13, "updateName"], [2, 11, "submitAction"], [2, 25, "submitAction"]]
118+
```js [[1, 5, "updateName"], [1, 15, "updateName"], [2, 13, "submitAction"], [2, 28, "submitAction"]]
119+
// UpdateName.js
116120
"use client";
117121

122+
import {useState, useTransition} from 'react';
118123
import {updateName} from './actions';
119124

120125
function UpdateName() {
@@ -123,40 +128,60 @@ function UpdateName() {
123128

124129
const [isPending, startTransition] = useTransition();
125130

126-
const submitAction = async () => {
131+
function submitAction() {
127132
startTransition(async () => {
128133
const {error} = await updateName(name);
134+
// State updates after await aren't automatically marked as Transitions,
135+
// so wrap them in another startTransition.
129136
startTransition(() => {
130-
if (error) {
131-
setError(error);
132-
} else {
137+
setError(error);
138+
if (!error) {
133139
setName('');
134140
}
135141
});
136-
})
142+
});
137143
}
138144

139145
return (
140146
<form action={submitAction}>
141-
<input type="text" name="name" disabled={isPending}/>
147+
<input
148+
type="text"
149+
name="name"
150+
value={name}
151+
onChange={event => setName(event.target.value)}
152+
disabled={isPending}
153+
/>
142154
{error && <span>Failed: {error}</span>}
143155
</form>
144-
)
156+
);
145157
}
146158
```
147159

148160
This allows you to access the `isPending` state of the Server Function by wrapping it in an Action on the client.
149161

150-
For more, see the docs for [Calling a Server Function outside of `<form>`](/reference/rsc/use-server#calling-a-server-function-outside-of-form)
162+
For more, see the docs for [Calling a Server Function outside of `<form>`](/reference/rsc/use-server#calling-a-server-function-outside-of-form).
151163

152-
### Server Functions with Form Actions {/*using-server-functions-with-form-actions*/}
164+
### Passing a Server Function to the `<form>` `action` prop {/*using-server-functions-with-form-actions*/}
153165

154166
Server Functions work with the new Form features in React 19.
155167

156-
You can pass a Server Function to a Form to automatically submit the form to the server:
168+
Pass a Server Function to the `<form>` `action` prop to submit the form to the server. React passes the submitted [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) to the Server Function as its first argument:
157169

170+
```js [[1, 4, "updateName"]]
171+
// actions.js
172+
"use server";
173+
174+
export async function updateName(formData) {
175+
const name = formData.get('name');
176+
if (typeof name !== 'string' || !name) {
177+
throw new Error('Name is required');
178+
}
179+
await db.users.updateName(name);
180+
}
181+
```
158182

159-
```js [[1, 3, "updateName"], [1, 7, "updateName"]]
183+
```js [[1, 4, "updateName"], [1, 8, "updateName"]]
184+
// UpdateName.js
160185
"use client";
161186

162187
import {updateName} from './actions';
@@ -166,50 +191,68 @@ function UpdateName() {
166191
<form action={updateName}>
167192
<input type="text" name="name" />
168193
</form>
169-
)
194+
);
170195
}
171196
```
172197

173-
When the Form submission succeeds, React will automatically reset the form. You can add `useActionState` to access the pending state, last response, or to support progressive enhancement.
198+
When the Server Function passed to the `<form>` `action` prop succeeds, React automatically resets the form's uncontrolled fields. Users can submit the form before its JavaScript bundle loads. Use `useActionState` to access the Action's pending state and most recent return value.
174199

175200
For more, see the docs for [Server Functions in Forms](/reference/rsc/use-server#server-functions-in-forms).
176201

177-
### Server Functions with `useActionState` {/*server-functions-with-use-action-state*/}
202+
### Calling a Server Function with `useActionState` {/*server-functions-with-use-action-state*/}
203+
204+
Call a Server Function with `useActionState` to access the Action's pending state and most recent return value. The Server Function receives the previous state as its first argument and the submitted [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) as its second argument. Its return value becomes the next state:
205+
206+
```js [[1, 4, "updateName"]]
207+
// actions.js
208+
"use server";
178209

179-
You can call Server Functions with `useActionState` for the common case where you just need access to the action pending state and last returned response:
210+
export async function updateName(previousState, formData) {
211+
const name = formData.get('name');
212+
if (typeof name !== 'string' || !name) {
213+
return {error: 'Name is required'};
214+
}
215+
await db.users.updateName(name);
216+
return {error: null};
217+
}
218+
```
180219

181-
```js [[1, 3, "updateName"], [1, 6, "updateName"], [2, 6, "submitAction"], [2, 9, "submitAction"]]
220+
```js [[1, 5, "updateName"], [1, 8, "updateName"], [2, 8, "submitAction"], [2, 11, "submitAction"]]
221+
// UpdateName.js
182222
"use client";
183223

224+
import {useActionState} from 'react';
184225
import {updateName} from './actions';
185226

186227
function UpdateName() {
187228
const [state, submitAction, isPending] = useActionState(updateName, {error: null});
188229

189230
return (
190231
<form action={submitAction}>
191-
<input type="text" name="name" disabled={isPending}/>
232+
<input type="text" name="name" disabled={isPending} />
192233
{state.error && <span>Failed: {state.error}</span>}
193234
</form>
194235
);
195236
}
196237
```
197238

198-
When using `useActionState` with Server Functions, React will also automatically replay form submissions entered before hydration finishes. This means users can interact with your app even before the app has hydrated.
239+
When the function passed to `useActionState` is a Server Function, users can submit the form before hydration finishes. React can display the Server Function's return value before JavaScript loads.
199240

200241
For more, see the docs for [`useActionState`](/reference/react/useActionState).
201242

202-
### Progressive enhancement with `useActionState` {/*progressive-enhancement-with-useactionstate*/}
243+
### Supporting progressive enhancement with `useActionState` {/*progressive-enhancement-with-useactionstate*/}
203244

204245
Server Functions also support progressive enhancement with the third argument of `useActionState`.
205246

206-
```js [[1, 3, "updateName"], [1, 6, "updateName"], [2, 6, "/name/update"], [3, 6, "submitAction"], [3, 9, "submitAction"]]
247+
```js [[1, 5, "updateName"], [1, 8, "updateName"], [2, 8, "/name/update"], [3, 8, "submitAction"], [3, 11, "submitAction"]]
248+
// UpdateName.js
207249
"use client";
208250

251+
import {useActionState} from 'react';
209252
import {updateName} from './actions';
210253

211254
function UpdateName() {
212-
const [, submitAction] = useActionState(updateName, null, `/name/update`);
255+
const [, submitAction] = useActionState(updateName, {error: null}, `/name/update`);
213256

214257
return (
215258
<form action={submitAction}>
@@ -219,6 +262,6 @@ function UpdateName() {
219262
}
220263
```
221264

222-
When the <CodeStep step={2}>permalink</CodeStep> is provided to `useActionState`, React will redirect to the provided URL if the form is submitted before the JavaScript bundle loads.
265+
If you pass the <CodeStep step={2}>`permalink`</CodeStep> to `useActionState`, the browser navigates to that URL when the form is submitted before the JavaScript bundle loads. At the destination, render the same form component with the same Server Function and `permalink` so React can pass the returned state to it.
223266

224267
For more, see the docs for [`useActionState`](/reference/react/useActionState).

0 commit comments

Comments
 (0)