import React, { useState, useEffect } from 'react'; import { useFieldArray, useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; // Zod Schema for validation const schema = z.object({ activityName: z.string().min(1, { message: "Activity name is required" }), unitOfMeasurement: z.string().min(1, { message: "Measurement is required" }), checkList: z .array(z.string().min(1, { message: "Checklist item cannot be empty" })) .optional(), } ); // for demo data let initialData = { activityName: "Item", unitOfMeasurement: "Item-2", checkList: [ 'item 3', 'Item 4' ] } const EditActivity = ({onClose}) => { const [isLoading, setIsLoading] = useState(false); const { register, handleSubmit, control, setValue, clearErrors, setError, getValues, reset, formState: { errors }, } = useForm({ resolver: zodResolver(schema), defaultValues: { activityName: '', unitOfMeasurement: '', checkList: [], }, }); // Setting up field array for checkList (dynamic fields) const { fields: checkListItems, append, remove, } = useFieldArray({ control, name: 'checkList', }); // Pre-populating the form with initial data when component mounts or initialData changes useEffect(() => { if (initialData) { reset({ activityName: initialData.activityName, unitOfMeasurement: initialData.unitOfMeasurement, checkList: initialData.checkList || [], }); } }, [initialData, reset]); // Form submission handler const onSubmit = (data) => { console.log('Submitted:', data); }; // Add a new checklist item const addChecklistItem = () => { const values = getValues('checkList'); const lastIndex = checkListItems.length - 1; // Prevent adding new input if the last one is empty if (checkListItems.length > 0 && (!values?.[lastIndex] || values[lastIndex].trim() === '')) { setError(`checkList.${lastIndex}`, { type: 'manual', message: 'Please fill this checklist item before adding another.', }); return; } clearErrors(`checkList.${lastIndex}`); // Clear the error if the input is filled. append(''); // Add a new empty checklist input }; // Remove a checklist item const removeChecklistItem = (index) => { remove(index); // Remove the checklist item from the field array }; // Handle checklist item input change const handleChecklistChange = (index, value) => { setValue(`checkList.${index}`, value); // Update the value of the checklist item }; const handleCLose = () => { () => reset() onClose() } return (
); }; export default EditActivity;