react.dev
react.dev copied to clipboard
[Typo]: In code example of server actions
trafficstars
Summary
In Composing Server Actions with Actions:
"use client";
import {updateName} from './actions';
function UpdateName() {
const [name, setName] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const submitAction = async () => {
startTransition(async () => {
const {error} = await updateName(name);
if (!error) {
setError(error);
} else {
setName('');
}
})
}
return (
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{state.error && <span>Failed: {state.error}</span>}
</form>
)
}
There is no state variable here.
It should be this
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{error && <span>Failed: {error}</span>}
</form>
Page
https://react.dev/reference/rsc/server-actions#composing-server-actions-with-actions
Details
No response
hello, is it valid?
"use server";
export async function updateName(name) {
if (!name) {
return {error: 'Name is required'};
}
await db.users.updateName(name);
}
"use client";
import {updateName} from './actions';
function UpdateName() {
const [name, setName] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const submitAction = async () => {
startTransition(async () => {
const {error} = await updateName(name);
if (!error) {
setError(error);
} else {
setName('');
}
})
}
return (
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{error && <span>Failed: {error}</span>}
</form>
)
}
I came here to create an issue for the same code, but we already have one. I know the example is kind of pseudo-code (we are not controlling the input, there is no submit button, etc.), but even with this, it should be error-free, I guess. There is one more mistake apart from state.error, which is
if (!error) {
setError(error);
...
it should be
if (error) {
setError(error);
...