react icon indicating copy to clipboard operation
react copied to clipboard

Feature Request: Reset form inside of Server Component or Action

Open FleetAdmiralJakob opened this issue 1 year ago • 13 comments

Hi, I want to be able to reset my form easily (after the action succeeded (so with the ability to react to a response of the server)) with JS Disabled and JS Enabled (if this is even possible).

The response of the server reaction thingy should be something like this:

-> On Success: The form should clear itself -> On Error: The input should keep it's content

FleetAdmiralJakob avatar Jan 04 '24 11:01 FleetAdmiralJakob

This feature is urgently needed as able to see in this discussion: https://github.com/vercel/next.js/discussions/58448

FleetAdmiralJakob avatar Jan 30 '24 19:01 FleetAdmiralJakob

hi @FleetAdmiralJakob can you explain more and tell the input the output u need more like what u have tried and failed

Eyuelb avatar Feb 03 '24 02:02 Eyuelb

@Eyuelb I tried to use useFormState but this was not resetting the form with JS Enabled. I tried to use useRef, but then I can't react to different cases (success, error) and also you loose the progressive enhancement.

FleetAdmiralJakob avatar Feb 03 '24 04:02 FleetAdmiralJakob

A quick fix is

export function processDataByType(data: any): any {
  if (typeof data === "string") {
    return "";
  } else if (typeof data === "boolean") {
    return data;
  } else if (Array.isArray(data)) {
    return [];
  } else {
    // You can handle other data types here if needed
    return null; // Default case, return null for other types
  }
}
Object.keys(formState.defaultValues)
.forEach((key:any) =>
 setValue(key,processDataByType(formState.defaultValues[key])
))

This basically resets the form

Eyuelb avatar Feb 03 '24 14:02 Eyuelb

OK, thank you @Eyuelb. But this seems like a lot of code for this very simple task. I can't imagine what other people have to do for their use cases. I will try this one out as fast as I can and give feedback. But I hope that there will be an easier solution in the future.

EDIT: I worry a little bit about alle the anys

FleetAdmiralJakob avatar Feb 03 '24 15:02 FleetAdmiralJakob

A quick fix is

`export function processDataByType(data: any): any { if (typeof data === "string") { return ""; } else if (typeof data === "boolean") { return data; } else if (Array.isArray(data)) { return []; } else { // You can handle other data types here if needed return null; // Default case, return null for other types } }

Object.keys(formState.defaultValues).forEach((key:any) => setValue(key,processDataByType(formState.defaultValues[key])))`

This basically resets the form

Could you pls format the code so it's easier to read.

FleetAdmiralJakob avatar Feb 03 '24 15:02 FleetAdmiralJakob

@FleetAdmiralJakob did you find a solution

Eyuelb avatar Feb 07 '24 13:02 Eyuelb

@Eyuelb Unfortunately not, I think React needs a general solution for this.

FleetAdmiralJakob avatar Feb 07 '24 15:02 FleetAdmiralJakob

A quick fix is export function processDataByType(data: any): any { if (typeof data === "string") { return ""; } else if (typeof data === "boolean") { return data; } else if (Array.isArray(data)) { return []; } else { // You can handle other data types here if needed return null; // Default case, return null for other types } } Object.keys(formState.defaultValues).forEach((key:any) => setValue(key,processDataByType(formState.defaultValues[key]))) This basically resets the form

Could you pls format the code so it's easier to read.

A quick fix is

export function processDataByType(data: any): any {
  if (typeof data === "string") {
    return "";
  } else if (typeof data === "boolean") {
    return data;
  } else if (Array.isArray(data)) {
    return [];
  } else {
    // You can handle other data types here if needed
    return null; // Default case, return null for other types
  }
}

Object.keys(formState.defaultValues).forEach((key: any) =>
  setValue(key, processDataByType(formState.defaultValues[key]))
);

This basically resets the form

PedroMarianoAlmeida avatar Feb 11 '24 03:02 PedroMarianoAlmeida

This post offers a solution by use of the key prop - santidalmasso

This is an alternative code snippet:

// actions.js

export async function submitFormAction(state, formData) {
  try {
    // do something
    return {
      ...state,
      error: null,
      resetKey: Date.now().toString(), // Generate a new resetKey to trigger form reset
    };
  } catch (error) {
    console.error("Error during form submission:", error);
    return {
      ...state,
      error: "Submission failed. Please try again.",
    };
  }
}
// FormComponent.js

import { useFormState } from "react-dom";
import { submitFormAction } from "./actions";

export default function SimpleForm() {
  const [response, submitForm] = useFormState(submitFormAction, undefined);

  return (
    <div className="form-container">
      <form action={submitForm} key={response?.resetKey}>
        <input type="text" placeholder="Your Input" name="inputField" />
        <button type="submit">Submit</button>
        {response?.error && <p>{response.error}</p>}
      </form>
    </div>
  );
}

matt-wigg avatar Feb 22 '24 08:02 matt-wigg

https://github.com/facebook/react/issues/29034#issue-2286939719

maybe allow opting out of automatic form reset is a good choice.

This is very necessary in the step-by-step form, such as verifying the email in the auth form first.

zce avatar May 14 '24 13:05 zce

https://github.com/facebook/react/issues/29034#issue-2286939719

maybe allow opting out of automatic form reset is a good choice.

This is very necessary in the step-by-step form, such as verifying the email in the auth form first.

The form shouldn't reset if any error on validation or w/e, but yeah, opting out may be reasonable too in some instances.

adriangalilea avatar May 14 '24 13:05 adriangalilea

One more thing: It's much easier to manually reset a form than to manually maintain its state

zce avatar May 14 '24 15:05 zce

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

github-actions[bot] avatar Aug 12 '24 16:08 github-actions[bot]

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

github-actions[bot] avatar Aug 19 '24 17:08 github-actions[bot]