Next.js Discord

Discord Forum

Reset Form using useFormState and server actions

Answered
West African Lion posted this in #help-forum
Open in Discord
West African LionOP
How to reset a form ? I don't see any documentation anywhere.

My use case:

I have one form that asks for an email.
When the user submits, it calls a server action that sends a code to that email address.
It then display a input to enter the code.

I want to add a "change address" button that will reset the form states (actually, the two forms, the one with the email and the one with the code) .

Any idea how to do so ?
Answered by joulev
"use client";
import { useRef } from "react";

export default function Page() {
  const form = useRef<HTMLFormElement | null>(null);

  return (
    <form ref={form}>
      <button
        type="button"
        onClick={() => {
          form.current?.reset();
        }}
      >
        Clear form
      </button>
    </form>
  );
}
View full answer

21 Replies

Answer
West African LionOP
Thanks @joulev .

In my case the form has already been submitted.

pseuco code :
  const [emailState, emailFormAction] = useFormState(sendCode, initialState);
  const [codeState, codeFormAction] = useFormState(checkCode, initialState);
  if (emailState.status !== "SUCCESS" || emailState.email === null) {
   <form action={emailFormAction}>
...
   </form>
}
if (codeState.status !== "SUCCESS") {
 <form action={codeFormAction} ref={codeFormRef}>
</form>
// TODO: ADD A "CHANGE EMAIL" button here
}
West African LionOP
I did this:

<button
onClick={() => {
             console.log("RESET FORMS");
             emailFormRef.current?.reset();
             codeFormRef.current?.reset();
           }}>
change email
</button>
this doesn't clear the form nor change the current state (emailState.status)
Should I add an extra state ?
make some dummy server action and a simple form that uses it
so i can clone and test
right now im just guessing because i can't test anything
West African LionOP
Yes. First I will try with an extra state / effect and if it works I will post the code here. 5mins
Thanks
sure np take your time
West African LionOP
Here is a fully working example !
I thought I could somehow write into the emailState, but I don't think that's possible.
Thanks for your help
@West African Lion Here is a fully working example !
so this is working right?
nice!
West African LionOP
Yes, it's totally working like this
Texas leafcutting ant
@West African Lion @joulev is it possible clear, for example, emailState.status error if i change data in email input? If i undestand right, emailState immutable there.
West African LionOP
@Texas leafcutting ant , indeed emailState.status is the status that comes back from the server action. You can't change it from the client.