Merge pull request 'feat: rewrite the form to react-hook-form and add validation' (#80) from feature/react-hook-form into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #80 Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
This commit is contained in:
commit
bd66f00b81
@ -86,6 +86,15 @@
|
||||
"dry-wash.arm.master.drawer.inputPhone.placeholder": "Enter Phone Number",
|
||||
"dry-wash.arm.master.drawer.button.save": "Save",
|
||||
"dry-wash.arm.master.drawer.button.cancel": "Cancel",
|
||||
"dry-wash.arm.master.drawer.toast.create-master": "Master created",
|
||||
"dry-wash.arm.master.drawer.toast.error.empty-fields": "Fields cannot be empty",
|
||||
"dry-wash.arm.master.drawer.toast.error.base": "Error",
|
||||
"dry-wash.arm.master.drawer.toast.error.create-master": "Error creating master",
|
||||
"dry-wash.arm.master.drawer.toast.error.create-master-details": "Failed to add master. Please try again",
|
||||
"dry-wash.arm.master.drawer.form.name.required": "Master name is required",
|
||||
"dry-wash.arm.master.drawer.form.phone.required": "Phone number is required",
|
||||
"dry-wash.arm.master.drawer.form.phone.pattern": "Invalid phone number",
|
||||
"dry-wash.arm.master.drawer.form.name.minLength": "Name must contain at least 2 characters",
|
||||
"dry-wash.arm.master.sideBar.orders": "Orders",
|
||||
"dry-wash.arm.master.sideBar.master": "Masters",
|
||||
"dry-wash.arm.master.sideBar.title": "Dry Master",
|
||||
|
@ -36,6 +36,15 @@
|
||||
"dry-wash.arm.master.drawer.inputPhone.placeholder": "Введите номер телефона",
|
||||
"dry-wash.arm.master.drawer.button.save": "Сохранить",
|
||||
"dry-wash.arm.master.drawer.button.cancel": "Отменить",
|
||||
"dry-wash.arm.master.drawer.toast.create-master": "Мастер создан",
|
||||
"dry-wash.arm.master.drawer.toast.error.empty-fields": "Поля не могут быть пустыми",
|
||||
"dry-wash.arm.master.drawer.toast.error.base": "Ошибка",
|
||||
"dry-wash.arm.master.drawer.toast.error.create-master": "Ошибка при создании мастера",
|
||||
"dry-wash.arm.master.drawer.toast.error.create-master-details": "Не удалось добавить мастера. Попробуйте еще раз",
|
||||
"dry-wash.arm.master.drawer.form.name.required": "Имя мастера обязательно",
|
||||
"dry-wash.arm.master.drawer.form.phone.required": "Телефон обязателен",
|
||||
"dry-wash.arm.master.drawer.form.phone.pattern": "Некорректный номер телефона",
|
||||
"dry-wash.arm.master.drawer.form.name.minLength": "Имя должно содержать минимум 2 символа",
|
||||
"dry-wash.arm.master.sideBar.orders": "Заказы",
|
||||
"dry-wash.arm.master.sideBar.master": "Мастера",
|
||||
"dry-wash.arm.master.sideBar.title": "Сухой мастер",
|
||||
|
@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm, SubmitHandler } from 'react-hook-form';
|
||||
import {
|
||||
Button,
|
||||
FormControl,
|
||||
@ -14,107 +15,136 @@ import {
|
||||
useToast,
|
||||
InputGroup,
|
||||
InputLeftElement,
|
||||
FormErrorMessage,
|
||||
} from '@chakra-ui/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PhoneIcon } from '@chakra-ui/icons';
|
||||
|
||||
import { api } from '../../__data__/service/api';
|
||||
import showToast from '../../helpers/showToast';
|
||||
import { DrawerInputs } from '../../models/arm/form';
|
||||
|
||||
const MasterDrawer = ({ isOpen, onClose }) => {
|
||||
const [addMaster, { error, isSuccess }] = api.useAddMasterMutation();
|
||||
const toast = useToast();
|
||||
interface MasterDrawerProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const [newMaster, setNewMaster] = useState({ name: '', phone: '' });
|
||||
const MasterDrawer = ({ isOpen, onClose }: MasterDrawerProps) => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<DrawerInputs>();
|
||||
|
||||
const handleSave = async () => {
|
||||
const { t } = useTranslation('~', {
|
||||
keyPrefix: 'dry-wash.arm.master.drawer',
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<DrawerInputs> = async (data) => {
|
||||
const trimMaster = {
|
||||
phone: newMaster.phone.trim(),
|
||||
name: newMaster.name.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
};
|
||||
|
||||
if (trimMaster.name === '' || trimMaster.phone === '') {
|
||||
const isEmptyFields = trimMaster.name === '' || trimMaster.phone === '';
|
||||
|
||||
if (isEmptyFields) {
|
||||
showToast({
|
||||
toast,
|
||||
title: t('toast.error.base'),
|
||||
description: t('toast.error.empty-fields'),
|
||||
status: 'error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
addMaster(trimMaster);
|
||||
await addMaster(trimMaster);
|
||||
};
|
||||
|
||||
const [addMaster, { error, isSuccess }] = api.useAddMasterMutation();
|
||||
const toast = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
if (isSuccess) {
|
||||
toast({
|
||||
title: 'Мастер создан.',
|
||||
description: `Мастер "${newMaster.name}" успешно добавлен.`,
|
||||
showToast({
|
||||
toast,
|
||||
title: t('toast.create-master'),
|
||||
status: 'success',
|
||||
duration: 5000,
|
||||
isClosable: true,
|
||||
position: 'top-right',
|
||||
});
|
||||
reset();
|
||||
onClose();
|
||||
}
|
||||
}, [isSuccess]);
|
||||
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Ошибка при создании мастера.',
|
||||
description: 'Не удалось добавить мастера. Попробуйте еще раз.',
|
||||
showToast({
|
||||
toast,
|
||||
title: t('toast.error.create-master'),
|
||||
description: t('toast.error.create-master-details'),
|
||||
status: 'error',
|
||||
duration: 5000,
|
||||
isClosable: true,
|
||||
position: 'top-right',
|
||||
});
|
||||
console.error(error);
|
||||
}
|
||||
}, [error]);
|
||||
|
||||
const { t } = useTranslation('~', {
|
||||
keyPrefix: 'dry-wash.arm.master.drawer',
|
||||
});
|
||||
|
||||
return (
|
||||
<Drawer isOpen={isOpen} onClose={onClose} size='md'>
|
||||
<DrawerOverlay />
|
||||
<DrawerContent>
|
||||
<DrawerCloseButton />
|
||||
<DrawerHeader>{t('title')}</DrawerHeader>
|
||||
<DrawerBody>
|
||||
<FormControl mb='4'>
|
||||
<FormLabel>{t('inputName.label')}</FormLabel>
|
||||
<Input
|
||||
// isInvalid
|
||||
value={newMaster.name}
|
||||
onChange={(e) =>
|
||||
setNewMaster({ ...newMaster, name: e.target.value })
|
||||
}
|
||||
placeholder={t('inputName.placeholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>{t('inputPhone.label')}</FormLabel>
|
||||
|
||||
<InputGroup>
|
||||
<InputLeftElement pointerEvents='none'>
|
||||
<PhoneIcon color='gray.300' />
|
||||
</InputLeftElement>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<DrawerCloseButton />
|
||||
<DrawerHeader>{t('title')}</DrawerHeader>
|
||||
<DrawerBody>
|
||||
<FormControl mb='4' isInvalid={!!errors.name}>
|
||||
<FormLabel>{t('inputName.label')}</FormLabel>
|
||||
<Input
|
||||
// isInvalid
|
||||
value={newMaster.phone}
|
||||
onChange={(e) =>
|
||||
setNewMaster({ ...newMaster, phone: e.target.value })
|
||||
}
|
||||
placeholder={t('inputPhone.placeholder')}
|
||||
{...register('name', {
|
||||
required: t('form.name.required'),
|
||||
minLength: {
|
||||
value: 2,
|
||||
message: t('form.name.minLength'),
|
||||
},
|
||||
})}
|
||||
placeholder={t('inputName.placeholder')}
|
||||
/>
|
||||
</InputGroup>
|
||||
</FormControl>
|
||||
</DrawerBody>
|
||||
<DrawerFooter>
|
||||
<Button colorScheme='teal' mr={3} onClick={handleSave}>
|
||||
{t('button.save')}
|
||||
</Button>
|
||||
<Button variant='ghost' onClick={onClose}>
|
||||
{t('button.cancel')}
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
<FormErrorMessage>
|
||||
{errors.name && errors.name.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!errors.phone}>
|
||||
<FormLabel>{t('inputPhone.label')}</FormLabel>
|
||||
<InputGroup>
|
||||
<InputLeftElement pointerEvents='none'>
|
||||
<PhoneIcon color='gray.300' />
|
||||
</InputLeftElement>
|
||||
<Input
|
||||
{...register('phone', {
|
||||
required: t('form.phone.required'),
|
||||
pattern: {
|
||||
value: /^(\+7|8)\d{10}$/,
|
||||
message: t('form.phone.pattern'),
|
||||
},
|
||||
setValueAs: (value) => value.replace(/[^\d+]/g, ''),
|
||||
})}
|
||||
placeholder={t('inputPhone.placeholder')}
|
||||
/>
|
||||
</InputGroup>
|
||||
<FormErrorMessage>
|
||||
{errors.phone && errors.phone.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</DrawerBody>
|
||||
<DrawerFooter>
|
||||
<Button colorScheme='teal' mr={3} type='submit'>
|
||||
{t('button.save')}
|
||||
</Button>
|
||||
<Button variant='ghost' onClick={onClose}>
|
||||
{t('button.cancel')}
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
</form>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
|
21
src/helpers/showToast.ts
Normal file
21
src/helpers/showToast.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { UseToastOptions } from '@chakra-ui/react';
|
||||
|
||||
interface ShowToast {
|
||||
toast: (options: UseToastOptions) => void;
|
||||
title: string;
|
||||
description?: string;
|
||||
status: 'info' | 'warning' | 'success' | 'error';
|
||||
}
|
||||
|
||||
const showToast = ({ toast, title, description, status }: ShowToast) => {
|
||||
toast({
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
duration: 5000,
|
||||
isClosable: true,
|
||||
position: 'top-right',
|
||||
});
|
||||
};
|
||||
|
||||
export default showToast;
|
4
src/models/arm/form.ts
Normal file
4
src/models/arm/form.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export type DrawerInputs = {
|
||||
phone: string;
|
||||
name: string;
|
||||
};
|
Loading…
Reference in New Issue
Block a user