Next.js Discord

Discord Forum

Is it just me or this example for Server Action not work?

Answered
Spectacled bear posted this in #help-forum
Open in Discord
Avatar
Spectacled bearOP
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#server-side-validation-and-error-handling

app/actions.ts
'use server'
 
export async function createUser(prevState: any, formData: FormData) {
  // ...
  return {
    message: 'Please enter a valid email',
  }
}

//app/ui/signup.tsx
'use client'
 
import { useFormState } from 'react-dom'
import { createUser } from '@/app/actions'
 
const initialState = {
  message: null,
}
 
export function Signup() {
  const [state, formAction] = useFormState(createUser, initialState) //typescript error right here
 
  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input type="text" id="email" name="email" required />
      {/* ... */}
      <p aria-live="polite" className="sr-only">
        {state?.message}
      </p>
      <button>Sign up</button>
    </form>
  )
}

This example gives typescript error
Answered by Withered Flowers
Since you're "returning" from the action an object with message as a string.
the initialState of a message should be a string too

// app/ui/signup.tsx
const initialState = {
  message: "" // change this from null to empty string
}


and yeah..... that's maybe a documentation error (maybe....), so you can try to PR it 😁
Image
View full answer

5 Replies

Avatar
B33fb0n3
Seems good for me… but you button is missing the „type=submit“ 😊
Avatar
Spectacled bearOP
Did you actually try in local dev or are you just saying it's looks good?
Avatar
Withered Flowers
Since you're "returning" from the action an object with message as a string.
the initialState of a message should be a string too

// app/ui/signup.tsx
const initialState = {
  message: "" // change this from null to empty string
}


and yeah..... that's maybe a documentation error (maybe....), so you can try to PR it 😁
Image
Answer
Avatar
B33fb0n3
Is it just me or this example for Server Action not work?
I just wanted to help you with the problem, why the server action not work 🙂
Avatar
Ray
sometime I will do
const initialState = {
  message: null,
} as Awaited<ReturnType<typeof createUser>>