Skip to content

Instantly share code, notes, and snippets.

@ellemedit
Created June 19, 2024 06:45
Show Gist options
  • Save ellemedit/da98e8483cf15f730df8da945462386e to your computer and use it in GitHub Desktop.
Save ellemedit/da98e8483cf15f730df8da945462386e to your computer and use it in GitHub Desktop.
A ReactDOM hook that allows you to reset form optionally after submitting

Example:

function Form() {
  const [isPending, onSubmit] = useFormActionHandler((formData, reset) => {
    if (formData.get('condition') === 'X') {
      reset();
    }
    // ...
  });
  
  return (
    <form onSubmit={onSubmit}>
      {...}
    </form>
  );
}
import { FormEvent, useTransition } from "react";
import { requestFormReset } from "react-dom";
// ref: https://github.com/facebook/react/issues/29034#issuecomment-2143595195
// default <form action={...} /> reset the whole form on submit
// this hook allows to reset the form conditionally
export function useFormActionHandler(
action: (formData: FormData, reset: () => void) => Promise<void>,
) {
const [isPending, startTransition] = useTransition();
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const reset = () => {
requestFormReset(event.currentTarget);
};
startTransition(async () => {
await action(formData, reset);
});
}
return [isPending, handleSubmit] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment