'use client'; import { useState, useRef } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { formAdtCreateSchema, type TFormAdtCreateValues } from './schemas'; import Image from 'next/image'; import { Category } from '@prisma/client'; import { useRouter } from 'next/navigation'; interface CreateAdtFormProps { categories: Category[]; } export default function AdtCreateForm({ categories }: CreateAdtFormProps) { const [isSubmitting, setIsSubmitting] = useState(false); const [preview, setPreview] = useState(null); const fileInputRef = useRef(null); const router = useRouter(); const { register, handleSubmit, formState: { errors }, reset, setValue, watch } = useForm({ resolver: zodResolver(formAdtCreateSchema), defaultValues: { categoryIds: [], } }); const selectedCategories = watch('categoryIds'); const handleImageChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { const reader = new FileReader(); reader.onloadend = () => { setPreview(reader.result as string); setValue('image', reader.result as string); }; reader.readAsDataURL(file); } }; const onSubmit = async (data: TFormAdtCreateValues) => { try { setIsSubmitting(true); const response = await fetch('/api/adt', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); if (!response.ok) { throw new Error('Ошибка при создании объявления'); } reset(); setPreview(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } // Здесь можно добавить уведомление об успешном создании const data_f = await response.json(); // Редирект на страницу созданного объявления router.push(`/adt/${data_f.id}`); // Обновляем кэш Next.js // router.refresh(); } catch (error) { console.error('Error:', error); // Здесь можно добавить обработку ошибок } finally { setIsSubmitting(false); } }; const handleCategoryChange = (categoryId: number) => { const currentCategories = watch('categoryIds') || []; const updatedCategories = currentCategories.includes(categoryId) ? currentCategories.filter(id => id !== categoryId) : [...currentCategories, categoryId]; setValue('categoryIds', updatedCategories); }; return (
{errors.title && (

{errors.title.message}

)}