DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

One tool for both registration and editing! Basic Techniques for Reusing Forms in React

Introduction

When building forms in React, haven't you hit this wall?
You ended up creating two separate forms for registration and editing...
But by using state effectively, you can consolidate them into a single form.

Solution

Create a mode to switch between registration and editing

const [mode, setMode] = useState<“create” | ‘edit’>(“create”);

“create” → New registration mode

“edit” → Editing mode
Enter fullscreen mode Exit fullscreen mode

Keep the data to be edited in state too

const [editing, setEditing] = useState<Record | null>(null);
Enter fullscreen mode Exit fullscreen mode

Store the record to be edited here
Set to null in registration mode

Set “mode” and “initial values” when opening the form

When in registration mode:
const openCreate = () => {
  setMode(“create”);
  setEditing(null);
  reset({ title: “”, time: 0 }); // Clear form
  onOpen(); // Open modal
};

When in edit mode:
const openEdit = (rec: Record) => {
  setMode(“edit”);
  setEditing(rec);
  reset({ title: rec.title, time: rec.time }); // Populate with existing data
  onOpen();
};
Enter fullscreen mode Exit fullscreen mode

Form submission can also be split based on mode

const onSubmit: SubmitHandler<Partial<Record>> = async (data) => {
  if (mode === “create”) {
    // Create new record
    await supabase.from(“study-record”).insert([
      { title: data.title, time: data.time },
    ]);
  } else if (mode === “edit” && editing) {
    // Update existing record
    await supabase
      .from(“study-record”)
      .update({ title: data.title, time: data.time })
      .eq(“id”, editing.id);
  }

  // Common post-processing
  reset();
  setMode(“create”);
  setEditing(null);
  onClose();
  fetchData();
};
Enter fullscreen mode Exit fullscreen mode

UI can also switch display based on mode

<ModalHeader>
  {mode === “edit” ? “Edit Record” : “New Registration”}
</ModalHeader>

<Button type="submit">
  {mode === “edit” ? ‘Update’ : “Register”}
</Button>
Enter fullscreen mode Exit fullscreen mode

Conclusion

By utilizing a state called “mode,” you can switch between registration and editing within a single form.
Using Supabase's .insert() and .update().eq(...) also enables database integration.

Top comments (0)