Skip to content

Unsaved useFieldArray items are lost after SWR revalidation #421

Description

@tssrkt

When editing an entry containing a list field, a newly added and already filled item can disappear before saving.

The issue is reproducible with lists of any length.

Steps to reproduce:

  1. Open an existing entry containing a list field.
  2. Click Add item.
  3. Fill the new item.
  4. Trigger SWR revalidation by switching browser focus, restoring the network connection, or waiting for another revalidation.
  5. Return to the form.

Expected result:

Unsaved local changes remain in the form.

Actual result:

The newly added item disappears. If Save is clicked afterward, the shortened list is submitted and successfully saved.

Probable cause:

The entry is loaded with SWR using focus and reconnect revalidation. After receiving the refreshed server content, defaultValues are recalculated and EntryForm unconditionally runs:

useEffect(() => {
  form.reset(defaultValues);
}, [defaultValues, form]);

This resets the form even when form.formState.isDirty is true and replaces the local useFieldArray state with the older server version.

Relevant code:

  • components/entry/entry-form.tsx: list initialization and append()
  • components/entry/entry-form.tsx: unconditional form.reset(defaultValues)
  • components/entry/entry.tsx: SWR focus and reconnect revalidation

Suggested minimal fix:

useEffect(() => {
  if (!form.formState.isDirty) {
    form.reset(defaultValues);
  }
}, [defaultValues, form, form.formState.isDirty]);

A more complete solution could show a warning when the server entry changes while the local form contains unsaved changes, and synchronize defaults after a successful save without overwriting newer local edits.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions