From f79f5ad412d871e731b93793c432481966498429 Mon Sep 17 00:00:00 2001 From: "ashutosh.nehete" Date: Fri, 27 Jun 2025 12:54:38 +0530 Subject: [PATCH] Create React Component with Form to Create New Service --- src/components/master/CreateServices.jsx | 123 +++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 src/components/master/CreateServices.jsx diff --git a/src/components/master/CreateServices.jsx b/src/components/master/CreateServices.jsx new file mode 100644 index 00000000..673d77f1 --- /dev/null +++ b/src/components/master/CreateServices.jsx @@ -0,0 +1,123 @@ +import React, { useEffect,useState } from 'react' +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { MasterRespository } from '../../repositories/MastersRepository'; +import { clearApiCacheKey } from '../../slices/apiCacheSlice'; +import { getCachedData,cacheData } 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 CreateServices = ({onClose}) => { + + const[isLoading,setIsLoading] = useState(false) + const { + register, + handleSubmit, + formState: { errors },reset + + } = useForm({ + resolver: zodResolver(schema), + defaultValues: { + name: "", + description: "", + + }, + }); + + const onSubmit = (data) => { + setIsLoading(true) + const result = { + name: data.name, + description: data.description, + }; + + MasterRespository.createService(result).then((resp)=>{ + setIsLoading(false) + resetForm() + const cachedData = getCachedData("Services"); + const updatedData = [...cachedData, resp?.data]; + cacheData("Services", updatedData); + showToast("Service Added successfully.", "success"); + + onClose() + }).catch((error)=>{ + showToast(error.message, "error"); + setIsLoading(false) + }) + + + }; + const resetForm = () => { + reset({ + name: "", + description: "" + }); + setDescriptionLength(0); + } + + useEffect(()=>{ + return ()=>resetForm() + },[]) + + const [descriptionLength, setDescriptionLength] = useState(0); + const maxDescriptionLength = 255; + return (<> +
+ {/*
+ +
*/} +
+ + + {errors.name &&

{errors.name.message}

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

{errors.description.message}

+ )} +
+ +
+ + +
+ +
+ + + ) +} + +export default CreateServices; \ No newline at end of file