#Resetting form inputs after form/fetcher submissions.

1 messages · Page 1 of 1 (latest)

fierce rock
#

Hello! I'm building out an app to learn the ins and outs of react router. I was wondering if there was any way to reset a form field after submitting a form.

For context, the app is a dumb little todo app. I wanted to use a fetcher to create a todo and then have the todos displayed on my app page as the user created todos. I thought it was correct to use a fetcher here, as I didn't really want to navigate away from this page on submission. I did want to revalidate the data from my loader which fetches the users todos from my server.

I've noticed that the fetcher.Form does not reset inputs after submitting a todo, which looks weird. My solution has been to use controlled components in a <form> and call fetcher.submit() to send the data to my action. In my <form> onSubmit function, I reset my controlled inputs after calling fetcher.submit().

Here's what I have:

export default function AppPage({ loaderData }: Route.ComponentProps) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const { userId, todos } = loaderData;

  const fetcher = useFetcher();

  async function handleSubmit(evt: React.FormEvent<HTMLFormElement>) {
    evt.preventDefault();

    // TODO: Build in some type of form validation eventually.
    await fetcher.submit({ title, description }, { method: 'POST' });

    setTitle('');
    setDescription('');
  }

  return (
    <div>
      <p>{userId}</p>
      <div>This is the App page.</div>

      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor='title'>Title</label>
          <input
            name='title'
            id='title'
            value={title}
            onChange={(evt) => setTitle(evt.target.value)}
          />
        </div>
        <div>
          <label htmlFor='description'>Description</label>
          <input
            name='description'
            id='description'
            value={description}
            onChange={(evt) => setDescription(evt.target.value)}
          />
        </div>
        <button>Submit?</button>
      </form>
      <TodoGrid todos={todos} />
    </div>
  );
}

If I am way off here, please let me know. As always, I appreciate all of your help. Thank you so much!

small pasture
#

you can clear uncontrolled inputs by changing a key on the form

fierce rock
#

I’m sorry, I’m not quite sure what you mean by a key on the form. Is there an attribute or something on forms that clears it after submission?