import { Box, Button, Drawer, DrawerBody, DrawerCloseButton, DrawerContent, DrawerFooter, DrawerHeader, DrawerOverlay, FormControl, FormErrorMessage, FormLabel, Input, Stack, useToast, } from "@chakra-ui/react"; import React, { useEffect, useRef, useState } from "react"; import { useForm, Controller } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import CustomAlertDialog from "../../Components/CustomAlertDialog"; import * as yup from "yup"; import ToastBox from "../../Components/ToastBox"; import { useUpdateKeyMeritsMutation } from "../../Services/io.service"; const keyMeritsSchema = yup.object().shape({ meritsHeader: yup.string().required("Title is required"), meritsDescription: yup.string().required("Sub title is required"), iconImage: yup.mixed().required("Icon is required"), // Adjust based on file or string }); const KeyMeritsEdit = ({ isOpen, onClose, firstField, id, actionId, data }) => { const toast = useToast() const [alert, setAlert] = useState(false); const [isLoading, setIsLoading] = useState(false); const [ editKeyMerits ] = useUpdateKeyMeritsMutation() const found = data?.find((item)=> item?.id === actionId) const { control, reset, handleSubmit, formState: { errors }, } = useForm({ resolver: yupResolver(keyMeritsSchema), }); // useEffect to reset the form when `found` changes useEffect(() => { if (found) { reset({ meritsHeader: found?.meritsHeader, meritsDescription: found?.meritsDescription, iconImage: null, }); } }, [found, reset]); const onSubmit = async (data) => { setIsLoading(true); try { const formData = new FormData(); formData.append("meritsHeader", data.meritsHeader); formData.append("meritsDescription", data.meritsDescription); if (data.iconImage && data.iconImage instanceof File) { formData.append("iconImage", data.iconImage); } const id = actionId const res = await editKeyMerits({ data: formData, id }); if (res?.data?.statusCode === 201) { toast({ render: () => , }); setAlert(false); onClose(); setIsLoading(false); reset() return } if(res?.error?.data?.code === 400){ toast({ render: () => , }); setAlert(false); onClose(); setIsLoading(false); reset() return } } catch (error) { if (error) { toast({ render: () => , }); } setIsLoading(false); setAlert(false); onClose(); reset() } reset() }; const handleSave = () => { handleSubmit(onSubmit)(); }; return ( <> Edit Key Merits Title ( )} /> {errors.meritsHeader?.message} Sub Title ( )} /> {errors.meritsDescription?.message} Icon ( { onChange(e.target.files[0]); }} onBlur={onBlur} fontSize={"sm"} size={"sm"} /> )} /> {errors.iconImage?.message} setAlert(false)} alertHandler={handleSave} message={"Are you sure you want to add this key merit?"} isLoading={isLoading} /> ); }; export default KeyMeritsEdit;