DEV Community

Dinh Doan Van Bien
Dinh Doan Van Bien

Posted on

Ensure the Conform useForm hook resets a form when the record id changes

Are you trying to implement a simple embedded edit form in using Conform? A form that lists all the records from a database, then when you click on one of the records, it should display the edit form as an outlet? And is your problem that when you display the form, the initial values do not got reset on the client side?

So what you need is to do an "Automatic form reset when id is changed" which is documented in the Tips section of useForm.

Here is the code that you are likely to be using. With this code, whenever your display an article the form will not be reset with the fields from the Article object.

interface Article {
  id: string;
  title: string;
  content: string;
}

function EditArticleForm({ defaultValue }: { defaultValue: Article }) {
  const [form, fields] = useForm({
    id: `edit-article`,
    defaultValue,
  });

  // ...
}
Enter fullscreen mode Exit fullscreen mode

What you need is to make sure the "id" field of the form gets updated as follows:

interface Article {
  id: string;
  title: string;
  content: string;
}

function EditArticleForm({ defaultValue }: { defaultValue: Article }) {
  const [form, fields] = useForm({
    id: `edit-article-${defaultValue.id}`,
    defaultValue,
  });

  // ...
}
Enter fullscreen mode Exit fullscreen mode

Just adding the ${defaultValue.id} bit will ensure the form initial values will be reset and reflect the values of the Article you want to edit.

Once you know it, it does make sense!

Top comments (0)