facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
228.3k stars 46.7k forks source link

Feature Request: Reset form inside of Server Component or Action #27876

Closed FleetAdmiralJakob closed 1 month ago

FleetAdmiralJakob commented 9 months ago

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 commented 8 months ago

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

Eyuelb commented 8 months ago

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

FleetAdmiralJakob commented 8 months ago

@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.

Eyuelb commented 8 months ago

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

FleetAdmiralJakob commented 8 months ago

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 commented 8 months ago

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.

Eyuelb commented 8 months ago

@FleetAdmiralJakob did you find a solution

FleetAdmiralJakob commented 8 months ago

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

PedroMarianoAlmeida commented 8 months ago

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

matt-wigg commented 7 months ago

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>
  );
}
zce commented 5 months ago

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.

adriangalilea commented 5 months ago

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.

zce commented 5 months ago

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

github-actions[bot] commented 2 months ago

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] commented 1 month ago

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!