File size: 3,275 Bytes
41a71fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
import { z } from 'zod';
import { useEffect } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { FormProvider, useForm } from 'react-hook-form';
import { useFetchPostById } from '@/entities/Post';
import { HInput } from '@/shared/ui/FormComponents';
import { classNames } from '@/shared/lib/classNames/classNames';
import { Button, ButtonSize, ButtonTheme } from '@/shared/ui/Button';
import { usePostStore } from '../../model/store/usePostStore';
import { useUpdatePost } from '../../lib/query/useUpdatePost';
import { useCreatePost } from '../../lib/query/useCreatePost';
import cls from './PostForm.module.scss';
const PostFormSchema = z.object({
title: z //
.string()
.min(1, { message: 'Заполните поле' })
.max(255),
body: z //
.string()
.min(1, { message: 'Заполните поле' })
.max(255),
});
export type PostFormType = z.infer<typeof PostFormSchema>;
interface PostFormProps {
className?: string;
}
const defaultValues = {
title: '',
body: '',
};
export const PostForm = (props: PostFormProps) => {
const { className } = props;
const editablePostId = usePostStore((state) => state.editablePostId);
const { data, isError, isLoading } = useFetchPostById(editablePostId);
const { mutate: create, isPending: isCreate } = useCreatePost();
const { mutate: update, isPending: isUpdate } = useUpdatePost();
const methods = useForm<PostFormType>({
defaultValues,
resolver: zodResolver(PostFormSchema),
});
const { handleSubmit, reset } = methods;
useEffect(() => {
if (data) {
reset({
title: data.title,
body: data.body,
});
} else {
reset(defaultValues);
}
}, [data]);
const submitHandler = async (data: PostFormType) => {
if (editablePostId) {
update({ ...data, post_id: editablePostId!, user_id: 1 });
} else {
create({ ...data, user_id: 1 });
}
};
if (isLoading) return <div>...Загружаем данные</div>;
if (isError) return <div>Что то пошло не так</div>;
return (
<div className={classNames(cls.PostForm, {}, [className])}>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(submitHandler)}>
<HInput //
className={cls.field}
name="title"
placeholder="Введите название"
/>
<HInput //
className={cls.field}
name="body"
placeholder="Введите описание"
/>
<Button
theme={ButtonTheme.PRIMARY}
size={ButtonSize.XL}
type="submit"
showSpinner={isCreate || isUpdate}
disabled={isCreate || isUpdate}
>
Сохранить
</Button>
</form>
</FormProvider>
</div>
);
};
|