From 9abf869704595a6731aa1791c283bc10ceb1014f Mon Sep 17 00:00:00 2001 From: "ashutosh.nehete" Date: Fri, 27 Jun 2025 12:55:55 +0530 Subject: [PATCH] Created React Component with Form to Update Service --- src/components/master/EditServices.jsx | 135 +++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 src/components/master/EditServices.jsx diff --git a/src/components/master/EditServices.jsx b/src/components/master/EditServices.jsx new file mode 100644 index 00000000..8fbf4b65 --- /dev/null +++ b/src/components/master/EditServices.jsx @@ -0,0 +1,135 @@ +import React, { useEffect, useState } from "react"; +import { useForm, Controller } from "react-hook-form"; +import { set, z } from "zod"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { MasterRespository } from "../../repositories/MastersRepository"; +import { cacheData, getCachedData } from "../../slices/apiDataManager"; +import showToast from "../../services/toastService"; + +const schema = z.object({ + name: z.string().min(1, { message: "Service Name is required" }), + description: z + .string() + .min(1, { message: "Description is required" }) + .max(255, { message: "Description cannot exceed 255 characters" }), +}); + +const EditServices = ({ data, onClose }) => { + const [isLoading, setIsLoading] = useState(false); + const { + register, + handleSubmit, + formState: { errors }, + reset, + watch, + } = useForm({ + resolver: zodResolver(schema), + defaultValues: { + name: data?.name || "", + description: data?.description || "", + }, + }); + + const selectedName = watch("name") + const selectedDescription = watch("description") + + const onSubmit = (formdata) => { + setIsLoading(true); + const result = { + id: data?.id, + name: formdata?.name, + description: formdata.description, + }; + + MasterRespository.updateService(data?.id, result) + .then((resp) => { + setIsLoading(false); + showToast("Service Update successfully.", "success"); + const cachedData = getCachedData("Services"); + if (cachedData) { + const updatedData = cachedData.map((service) => + service.id === data?.id ? { ...service, ...resp.data } : service + ); + cacheData("Services", updatedData); + } + + onClose(); + }) + .catch((error) => { + showToast(error.message, "error"); + setIsLoading(false); + }); + }; + + useEffect(() => { + reset({ + name: data?.name, + description: data?.description, + }); + setDescriptionLength(data?.description?.length || 0); + }, [data, reset]); + + const [descriptionLength, setDescriptionLength] = useState( + data?.description?.length || 0 + ); + const maxDescriptionLength = 255; + + return ( + <> +
+ {/*
+ +
*/} +
+ + + {errors.name &&

{errors.name.message}

} +
+
+ + +
+ {maxDescriptionLength - descriptionLength} characters left +
+ {errors.description && ( +

{errors.description.message}

+ )} +
+ +
+ + +
+
+ + ); +}; + +export default EditServices;