To achieve the desired functionality where only the user-filled or changed fields are included in the request payload during form submission, you can leverage React Hook Form's dirtyFields and perform selective data extraction based on whether the form is in "create" or "edit" mode.
Here's a comprehensive guide to implementing this behavior in your ItemForm component:
1. Determine Create vs. Edit Mode
First, you need to distinguish between creating a new item and editing an existing one. This can typically be done by checking if defaultValues are provided or by introducing a separate prop (e.g., isEdit).
export const ItemForm = ({ defaultValues = {}, onSubmit }) => {
const isEdit = Boolean(defaultValues && Object.keys(defaultValues).length > 0);
// Rest of the form setup...
};
2. Utilize dirtyFields for Edit Mode
React Hook Form tracks which fields have been modified using the dirtyFields object. You can use this to extract only the fields that have changed during an edit.
3. Extract Non-Empty Fields for Create Mode
When creating a new item, you'll want to include only the fields that the user has filled out. This means excluding fields that are empty, null, or undefined.
4. Implement Helper Functions
Create utility functions to help extract the necessary fields based on the mode.
// Utility to recursively extract changed fields based on dirtyFields
const extractChangedFields = (data, dirtyFields) => {
let changed = {};
for (const key in dirtyFields) {
if (typeof dirtyFields[key] === 'object' && !Array.isArray(dirtyFields[key])) {
const nested = extractChangedFields(data[key], dirtyFields[key]);
if (Object.keys(nested).length > 0) {
changed[key] = nested;
}
} else if (Array.isArray(dirtyFields[key])) {
changed[key] = data[key].map((item, index) => {
if (dirtyFields[key][index]) {
return extractChangedFields(item, dirtyFields[key][index]);
}
return null;
}).filter(item => item !== null);
} else {
changed[key] = data[key];
}
}
return changed;
};
// Utility to recursively extract non-empty fields
const extractFilledFields = (data) => {
let filled = {};
for (const key in data) {
const value = data[key];
if (typeof value === 'object' && value !== null) {
if (Array.isArray(value)) {
const arrayFilled = value.map(item => extractFilledFields(item)).filter(item => Object.keys(item).length > 0);
if (arrayFilled.length > 0) {
filled[key] = arrayFilled;
}
} else {
const nestedFilled = extractFilledFields(value);
if (Object.keys(nestedFilled).length > 0) {
filled[key] = nestedFilled;
}
}
} else if (value !== undefined && value !== null && value !== '') {
filled[key] = value;
}
}
return filled;
};
5. Modify the Submit Handler
Update the handleFormSubmit function to utilize these helper functions based on the form mode.
const handleFormSubmit = (data) => {
let payload = {};
if (isEdit) {
payload = extractChangedFields(data, dirtyFields);
} else {
payload = extractFilledFields(data);
}
console.log('Payload to send:', payload);
onSubmit(payload); // Call the original onSubmit prop with the processed payload
};
6. Complete Updated Component
Below is the complete updated ItemForm component incorporating the above changes:
import React, { useEffect } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import styles from './ItemForm.module.css';
// Define the validation schema using Yup
const schema = yup.object({
name: yup
.string()
.required('Name is required')
.max(50, 'Max length is 50 characters'),
category: yup.string().required('Category is required'),
quantity: yup
.number()
.typeError('Quantity must be a number')
.required('Quantity is required')
.min(1, 'Quantity must be at least 1'),
location: yup.string().notRequired(),
supplier: yup.string().notRequired(),
supplierLocation: yup.string().notRequired(),
showPriceDetails: yup
.string()
.oneOf(['yes', 'no'], 'Please select an option')
.required('Please select an option'),
priceType: yup
.string()
.when('showPriceDetails', {
is: 'yes',
then: (schema) => schema.required('Price Type is required'),
otherwise: (schema) => schema.notRequired(),
}),
price: yup
.number()
.transform((value, originalValue) => (originalValue === '' ? undefined : value))
.when('showPriceDetails', {
is: 'yes',
then: (schema) =>
schema
.required('Price is required')
.typeError('Price must be a number')
.min(1, 'Price must be at least 1'),
otherwise: (schema) => schema.notRequired(),
}),
endpoints: yup.array().of(
yup.object({
endpoint: yup.string().required('Endpoint is required'),
status: yup.string().required('Status is required'),
})
),
});
// Utility to recursively extract changed fields based on dirtyFields
const extractChangedFields = (data, dirtyFields) => {
let changed = {};
for (const key in dirtyFields) {
if (typeof dirtyFields[key] === 'object' && !Array.isArray(dirtyFields[key])) {
const nested = extractChangedFields(data[key], dirtyFields[key]);
if (Object.keys(nested).length > 0) {
changed[key] = nested;
}
} else if (Array.isArray(dirtyFields[key])) {
changed[key] = data[key].map((item, index) => {
if (dirtyFields[key][index]) {
return extractChangedFields(item, dirtyFields[key][index]);
}
return null;
}).filter(item => item !== null);
} else {
changed[key] = data[key];
}
}
return changed;
};
// Utility to recursively extract non-empty fields
const extractFilledFields = (data) => {
let filled = {};
for (const key in data) {
const value = data[key];
if (typeof value === 'object' && value !== null) {
if (Array.isArray(value)) {
const arrayFilled = value.map(item => extractFilledFields(item)).filter(item => Object.keys(item).length > 0);
if (arrayFilled.length > 0) {
filled[key] = arrayFilled;
}
} else {
const nestedFilled = extractFilledFields(value);
if (Object.keys(nestedFilled).length > 0) {
filled[key] = nestedFilled;
}
}
} else if (value !== undefined && value !== null && value !== '') {
filled[key] = value;
}
}
return filled;
};
export const ItemForm = ({ defaultValues = {}, onSubmit }) => {
const isEdit = Boolean(defaultValues && Object.keys(defaultValues).length > 0);
const {
register,
handleSubmit,
watch,
control,
formState: { errors, dirtyFields },
reset,
} = useForm({
defaultValues,
resolver: yupResolver(schema),
});
const { fields, append, remove } = useFieldArray({
control,
name: 'endpoints',
});
const showPriceDetails = watch('showPriceDetails') === 'yes';
useEffect(() => {
reset(defaultValues);
}, [defaultValues, reset]);
// Custom submit handler that logs affected fields
const handleFormSubmit = (data) => {
let payload = {};
if (isEdit) {
payload = extractChangedFields(data, dirtyFields);
} else {
payload = extractFilledFields(data);
}
console.log('Payload to send:', payload);
onSubmit(payload); // Call the original onSubmit prop with the processed payload
};
return (
<div className={styles.formContainer}>
<form onSubmit={handleSubmit(handleFormSubmit)} className={styles.formWrapper}>
{/* Basic Information */}
<div className={`${styles.formGrid} ${styles.grid3}`}>
{/* Name */}
<div className={styles.formGroup}>
<label htmlFor="name">Name*:</label>
<input
id="name"
{...register('name')}
className={errors.name ? styles.inputError : ''}
/>
{errors.name && <p className={styles.errorMessage}>{errors.name.message}</p>}
</div>
{/* Category */}
<div className={styles.formGroup}>
<label htmlFor="category">Category*:</label>
<select
id="category"
{...register('category')}
className={errors.category ? styles.inputError : ''}
>
<option value="">Select category</option>
<option value="Electronics">Electronics</option>
<option value="Furniture">Furniture</option>
<option value="Clothing">Clothing</option>
<option value="Food">Food</option>
<option value="Toys">Toys</option>
<option value="Books">Books</option>
<option value="Sports">Sports</option>
</select>
{errors.category && (
<p className={styles.errorMessage}>{errors.category.message}</p>
)}
</div>
{/* Quantity */}
<div className={styles.formGroup}>
<label htmlFor="quantity">Quantity*:</label>
<input
id="quantity"
type="number"
{...register('quantity')}
className={errors.quantity ? styles.inputError : ''}
/>
{errors.quantity && (
<p className={styles.errorMessage}>{errors.quantity.message}</p>
)}
</div>
</div>
{/* Optional Fields */}
<div className={`${styles.formGrid} ${styles.grid2}`}>
{/* Supplier */}
<div className={styles.formGroup}>
<label htmlFor="supplier">Supplier:</label>
<input
id="supplier"
{...register('supplier')}
className={errors.supplier ? styles.inputError : ''}
/>
{errors.supplier && (
<p className={styles.errorMessage}>{errors.supplier.message}</p>
)}
</div>
{/* Supplier Location */}
<div className={styles.formGroup}>
<label htmlFor="supplierLocation">Supplier Location:</label>
<input
id="supplierLocation"
{...register('supplierLocation')}
className={errors.supplierLocation ? styles.inputError : ''}
/>
{errors.supplierLocation && (
<p className={styles.errorMessage}>{errors.supplierLocation.message}</p>
)}
</div>
</div>
{/* Radio Button to Show Additional Fields */}
<div className={styles.formGroup}>
<label>Show Price Details?</label>
<div className={styles.radioGroup}>
<label>
<input
type="radio"
value="yes"
{...register('showPriceDetails')}
defaultChecked={defaultValues?.showPriceDetails === 'yes'}
/>
Yes
</label>
<label>
<input
type="radio"
value="no"
{...register('showPriceDetails')}
defaultChecked={defaultValues?.showPriceDetails !== 'yes'}
/>
No
</label>
</div>
{errors.showPriceDetails && (
<p className={styles.errorMessage}>{errors.showPriceDetails.message}</p>
)}
</div>
{/* Additional Price Details */}
{showPriceDetails && (
<div className={`${styles.formGrid} ${styles.grid2}`}>
{/* Price Type */}
<div className={styles.formGroup}>
<label htmlFor="priceType">Price Type*:</label>
<select
id="priceType"
{...register('priceType')}
className={errors.priceType ? styles.inputError : ''}
>
<option value="">Select type</option>
<option value="For Sale">For Sale</option>
<option value="For Buying">For Buying</option>
</select>
{errors.priceType && (
<p className={styles.errorMessage}>{errors.priceType.message}</p>
)}
</div>
{/* Price */}
<div className={styles.formGroup}>
<label htmlFor="price">Price*:</label>
<input
id="price"
type="number"
{...register('price')}
className={errors.price ? styles.inputError : ''}
placeholder="Enter price"
/>
{errors.price && (
<p className={styles.errorMessage}>{errors.price.message}</p>
)}
</div>
</div>
)}
{/* Endpoints Array Field */}
<div className={`${styles.formGroup} ${styles.fullWidth}`}>
<h3>Endpoints</h3>
{fields.map((field, index) => (
<div key={field.id} className={`${styles.formGrid} ${styles.grid2}`}>
{/* Endpoint Name */}
<div className={styles.formGroup}>
<label htmlFor={`endpoints.${index}.endpoint`}>Endpoint {index + 1}*:</label>
<input
id={`endpoints.${index}.endpoint`}
{...register(`endpoints.${index}.endpoint`)}
className={
errors.endpoints?.[index]?.endpoint ? styles.inputError : ''
}
/>
{errors.endpoints?.[index]?.endpoint && (
<p className={styles.errorMessage}>
{errors.endpoints[index].endpoint.message}
</p>
)}
</div>
{/* Status */}
<div className={styles.formGroup}>
<label htmlFor={`endpoints.${index}.status`}>Status*:</label>
<select
id={`endpoints.${index}.status`}
{...register(`endpoints.${index}.status`)}
className={
errors.endpoints?.[index]?.status ? styles.inputError : ''
}
>
<option value="">Select status</option>
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
<option value="Completed">Completed</option>
</select>
{errors.endpoints?.[index]?.status && (
<p className={styles.errorMessage}>
{errors.endpoints[index].status.message}
</p>
)}
</div>
{/* Remove Endpoint Button */}
<div className={styles.formGroup}>
<button
type="button"
className={styles.removeEndpointButton}
onClick={() => remove(index)}
>
Remove
</button>
</div>
</div>
))}
{/* Add Endpoint Button */}
<button
type="button"
className={styles.addEndpointButton}
onClick={() => append({ endpoint: '', status: '' })}
>
Add Endpoint
</button>
</div>
{/* Submit Button */}
<button type="submit" className={styles.actionButton}>
Submit
</button>
</form>
</div>
);
};
7. Handling Arrays (endpoints)
Handling dynamic arrays like endpoints requires special attention:
-
Create Mode: When adding new endpoints, only include the ones that the user has filled out (i.e., non-empty).
-
Edit Mode: Detect which endpoints have been added, removed, or modified. The extractChangedFields function provided earlier handles this by comparing each item in the array.
8. Server-Side Considerations
Ensure that your server can handle partial updates:
-
Create: The server should accept partial data and populate default values for missing fields if necessary.
-
Edit: The server should merge the received partial data with existing data or update only the specified fields.
9. Example Usage
Here's how you might use the ItemForm component in a parent component:
import React from 'react';
import { ItemForm } from './ItemForm';
const ParentComponent = () => {
const handleSubmit = (payload) => {
// Determine if it's a create or edit action
// For example, based on the presence of an ID
const isEdit = Boolean(payload.id);
const url = isEdit ? `/api/items/${payload.id}` : '/api/items';
const method = isEdit ? 'PATCH' : 'POST';
fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
.then(response => response.json())
.then(data => {
// Handle success
console.log('Success:', data);
})
.catch((error) => {
// Handle error
console.error('Error:', error);
});
};
// Example defaultValues for edit mode
const defaultValues = {
name: 'Sample Item',
category: 'Electronics',
quantity: 10,
supplier: 'ABC Supplies',
supplierLocation: 'New York',
showPriceDetails: 'yes',
priceType: 'For Sale',
price: 99.99,
endpoints: [
{ endpoint: 'Endpoint 1', status: 'Active' },
{ endpoint: 'Endpoint 2', status: 'Inactive' },
],
};
return (
<div>
{/* For Create Mode */}
<ItemForm onSubmit={handleSubmit} />
{/* For Edit Mode */}
{/* <ItemForm defaultValues={defaultValues} onSubmit={handleSubmit} /> */}
</div>
);
};
export default ParentComponent;
10. Testing the Implementation
-
Create Mode: Render the ItemForm without defaultValues and try submitting the form with various fields filled out. Check the console to ensure only the filled fields are included in the payload.
-
Edit Mode: Render the ItemForm with defaultValues and modify different fields. Ensure that only the changed fields are included in the payload upon submission.
11. Additional Enhancements
-
Performance Optimization: For large forms, consider memoizing the helper functions to prevent unnecessary computations.
-
User Feedback: Provide visual indicators for unsaved changes or display which fields have been modified.
-
Error Handling: Implement comprehensive error handling both on the client and server sides to handle scenarios where partial updates fail.
12. Summary
By leveraging React Hook Form's dirtyFields and implementing helper functions to extract only the necessary fields based on the form mode (create or edit), you can ensure that your request payloads are optimized and contain only the relevant data. This approach not only improves performance but also aligns with best practices for data management and API interactions.
Feel free to adjust and extend the helper functions based on the specific requirements and complexities of your form structure.