Next.js Discord

Discord Forum

How to run async/await code with useFormState action

Answered
Atlantic mackerel posted this in #help-forum
Open in Discord
Atlantic mackerelOP
Without using useFormState hook, I can do something like this
export default function Form() {
  const [someState, setSomeState] = useState(0);
  async function onSubmit(formData: FormData) {
    await serverAction(formData)
    setSomeState(1)
  }
  return (
    <form action={onSubmit}>
      <input name="name"/>
    </form>
  )
}

But I can't when using useFormState since the returned formAction doesn't return a promise
export default function Form() {
  const [someState, setSomeState] = useState(0);
  const [formState, formAction] = useFormState(serverAction, {})
  async function onSubmit(formData: FormData) {
    await formAction(formData)
    setSomeState(1) // doesn't await formAction 
  }
  return (
    <form action={onSubmit}>
      <input name="name"/>
    </form>
  )
}

Or am I misusing the hook?
Answered by Arinji
just dont use useFormState if you are tryna await it
View full answer

19 Replies

@Atlantic mackerel
useActionState is to use the action inside the form directly
Thats how you use it'
hence why you cant just await it
React 19 includes a new hook to be able to useActionState and get nice pending states.. but its not in nextjs yet (probs experimental or in canary).. so till then you just need to do the normal state method
Atlantic mackerelOP
I read the useActionState docs but it seems to be the same as useFormState
@Arinji did you read the react.dev docs?
Atlantic mackerelOP
yes
have you tried using it? does it let you await the action?
thats all i see currently abt useFormState
thing is, thats introducted in react 19
so dont go thru the docs rn
since we still on react 18
just dont use useFormState if you are tryna await it
Answer
Atlantic mackerelOP
ok then I'll wait for v19
@Arinji thanks a lot!