diff --git a/src/components/Modals/EditCategoryModal/EditCategoryModal.tsx b/src/components/Modals/EditCategoryModal/EditCategoryModal.tsx new file mode 100644 index 0000000..aedd665 --- /dev/null +++ b/src/components/Modals/EditCategoryModal/EditCategoryModal.tsx @@ -0,0 +1,94 @@ +import React from 'react'; +import BaseModal from '@educt/components/Modal'; +import { ICategory } from '@educt/interfaces'; +import { MdModeEdit } from 'react-icons/md'; +import { FormControl, FormLabel, FormHelperText, Stack, Input, Textarea } from '@chakra-ui/react'; +import { UpdateCategoryParamsType } from '@educt/types'; +import { yupResolver } from '@hookform/resolvers/yup'; + +/** + * Schema + */ +import EditCategorySchema from './EditCategoryModal.validator'; +import { useUpdateCategory } from '@educt/hooks/queries'; + +/** + * Hooks + */ +import { useEffect, useMemo } from 'react'; +import { useForm } from 'react-hook-form'; + +type EditCategoryModalPropsType = { + category: ICategory; + isOpen: boolean; + onClose: () => void; + onEdited?: (updatedCategory: ICategory) => void | undefined; +}; + +type UpdateCategoryInputType = { + title?: string | undefined; + description?: string | undefined; +}; + +const EditCategoryModal: React.FC = props => { + const { category, onClose, onEdited, isOpen } = props; + const defaultValues = { + title: category.title, + description: category.description, + }; + const { + register, + handleSubmit, + reset, + formState: { errors, isDirty }, + } = useForm({ + resolver: yupResolver(EditCategorySchema), + defaultValues: useMemo(() => { + return defaultValues; + }, [props]), + }); + const { updateCategory, isLoading } = useUpdateCategory(); + + const onSubmit = async (data: UpdateCategoryParamsType) => { + try { + const updated = await updateCategory(category.id, data); + onClose(); + onEdited && onEdited(updated); + } catch (error) { + console.error(error); + } + }; + + useEffect(() => { + reset(defaultValues); + }, [props.category]); + + return ( + + + + Name + + {errors.title && {errors?.title.message}} + + + + Description +