Product CRUD: Form Frontend đầy đủ state
CRUD form thường bị viết như mộtuseState() lớn + fetch + tự map lỗi. Inertia useForm đã cung cấp hầu hết lifecycle state cần thiết.
Form data nên phù hợp với input trước
price để string ở UI vì <input> thực tế làm việc với text. Chuyển sang number ở boundary submit bằng transform().
Keyed useForm
Create:
EditProduct dùng chung cho mọi record sẽ tạo collision state.
Clear field error khi người dùng sửa lại
Submit có transform
fetch() và parse 422 JSON. Khi Laravel redirect validation errors, Inertia đưa lỗi về form.errors.
Loading state
Error state
Dirty state
isDirty để:
- disable submit khi chưa thay đổi;
- cảnh báo trước khi đóng modal;
- hiển thị unsaved badge;
- quyết định có reset form hay không.
Cancel request
Success state cục bộ
recentlySuccessful cho feedback rất tự nhiên.
Create và Edit dùng cùng component
ProductForm chỉ sở hữu presentation/interaction. Page create/edit sở hữu endpoint và intent submit.
Đây là separation tốt hơn việc component form tự đoán đang create hay edit qua nullable ID.
Upload ảnh và progress
Phần image lifecycle được tách riêng để không làm form cơ bản quá tải. Đọc tiếp Product CRUD: upload ảnh, preview và progress.Full source
Khi nào dùng <Form> thay useForm?
Dùng <Form> khi bạn muốn declarative form gần với HTML form và ít imperative logic. Dùng useForm khi:
- form có derived interaction;
- cần programmatic
setData; - cần nhiều button/intent;
- cần
transformtheo state runtime; - cần truy cập lifecycle state ở nhiều component.
useForm vì mục tiêu là trình diễn đầy đủ state machine của form.