|
| 1 | +import { zodResolver } from '@hookform/resolvers/zod' |
| 2 | +import { useState } from 'react' |
| 3 | +import { useForm } from 'react-hook-form' |
| 4 | +import { toast } from 'react-hot-toast' |
| 5 | +import { z } from 'zod' |
| 6 | + |
| 7 | +import { classNames } from '@/utils/classNames' |
| 8 | +import { generateKey } from '@/utils/generateKey' |
| 9 | +import { trpc } from '@/utils/trpc' |
| 10 | + |
| 11 | +import { Textarea } from '../common/Textarea' |
| 12 | +import { SubmitButton } from '../dashboard/common/Buttons' |
| 13 | + |
| 14 | +const schema = z.object({ |
| 15 | + message: z.string().min(4, 'Review must be 4 characters long.'), |
| 16 | +}) |
| 17 | +type ISchema = z.infer<typeof schema> |
| 18 | +type RatingformProps = { |
| 19 | + handleClose: () => void |
| 20 | + productId: string |
| 21 | +} |
| 22 | + |
| 23 | +export function Ratingform({ productId, handleClose }: RatingformProps) { |
| 24 | + const review = trpc.review.add.useMutation() |
| 25 | + const [rating, setRating] = useState(0) |
| 26 | + const [hover, setHover] = useState(0) |
| 27 | + const { |
| 28 | + register, |
| 29 | + handleSubmit, |
| 30 | + formState: { errors, isSubmitting }, |
| 31 | + } = useForm<ISchema>({ |
| 32 | + resolver: zodResolver(schema), |
| 33 | + }) |
| 34 | + async function submit(val: ISchema) { |
| 35 | + await review.mutate( |
| 36 | + { ...val, rating, productId }, |
| 37 | + { |
| 38 | + onSuccess() { |
| 39 | + handleClose() |
| 40 | + toast.success('Rating added') |
| 41 | + }, |
| 42 | + } |
| 43 | + ) |
| 44 | + } |
| 45 | + return ( |
| 46 | + <form onSubmit={handleSubmit((v) => submit(v))} className="space-y-4"> |
| 47 | + {review.isError ? ( |
| 48 | + <p className="text-red-500">{review.error.message}</p> |
| 49 | + ) : null} |
| 50 | + <div> |
| 51 | + <p>Rating</p> |
| 52 | + {Array.from({ length: 5 }).map((v, i) => ( |
| 53 | + <button |
| 54 | + className={classNames( |
| 55 | + 'border-none outline-none bg-transparent', |
| 56 | + i + 1 <= ((rating && hover) || hover) |
| 57 | + ? 'dark:text-gray-300 text-gray-800' |
| 58 | + : 'dark:text-gray-700 text-gray-300' |
| 59 | + )} |
| 60 | + type="button" |
| 61 | + key={generateKey()} |
| 62 | + onDoubleClick={() => { |
| 63 | + setRating(0) |
| 64 | + setHover(0) |
| 65 | + }} |
| 66 | + onMouseEnter={() => setHover(i + 1)} |
| 67 | + onMouseLeave={() => setHover(rating)} |
| 68 | + onClick={() => setRating(i + 1)} |
| 69 | + > |
| 70 | + <span className="text-2xl md:text-4xl">★</span> |
| 71 | + </button> |
| 72 | + ))} |
| 73 | + </div> |
| 74 | + <Textarea |
| 75 | + error={errors.message} |
| 76 | + rows={5} |
| 77 | + placeholder="Review..." |
| 78 | + label="Review" |
| 79 | + {...register('message')} |
| 80 | + /> |
| 81 | + <SubmitButton disabled={isSubmitting || review.isLoading} /> |
| 82 | + </form> |
| 83 | + ) |
| 84 | +} |
0 commit comments