react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

[Typo]: In code example of server actions

Open patelvivekdev opened this issue 1 year ago • 3 comments
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

patelvivekdev avatar May 01 '24 03:05 patelvivekdev

hello, is it valid?

ijayhub avatar May 27 '24 14:05 ijayhub

"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>
  )
}

patelvivekdev avatar May 27 '24 20:05 patelvivekdev

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);
...

devserkan avatar Jun 17 '24 22:06 devserkan