diff --git a/app/(prizes)/prizes/[user_id]/page.tsx b/app/(prizes)/prizes/[user_id]/page.tsx index d97aaab..4a0b067 100644 --- a/app/(prizes)/prizes/[user_id]/page.tsx +++ b/app/(prizes)/prizes/[user_id]/page.tsx @@ -3,6 +3,8 @@ import PrizeCard from '@/components/prizes/PrizeCard'; import { useState } from 'react'; import axios from 'axios'; import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { GiftsType } from '@/typings/gifts/gifts.type'; +import { useRouter } from 'next/navigation'; // Define the expected shape of the fetched data interface Prize { @@ -14,29 +16,43 @@ interface Prize { const PrizesPage = ({ params }: { params: { user_id: string } }) => { const [selectedPrize, setSelectedPrize] = useState(null); const queryClient = useQueryClient(); + const router = useRouter(); // Fetching data using TanStack Query - const { data, isLoading, error } = useQuery( - [`gifts-${params.user_id}`, params.user_id], // Query key using user_id + const { data, isLoading, error } = useQuery( + [`gifts-${params.user_id}`, params.user_id, selectedPrize], // Query key using user_id () => axios .get(`https://sms.turkmentv.gov.tm/api/gifts/${params.user_id}`) .then((response) => response.data), { staleTime: 60000, // Cache data for 1 minute - initialData: () => queryClient.getQueryData([`gifts-${params.user_id}`]), + // Handle error with onError callback to trigger the redirect + onError: () => { + router.push('/prizes/auth'); + }, }, ); - if (isLoading) return

Loading...

; - if (error) return

Error loading prizes: {error.message}

; + if (isLoading) + return ( +
+ Loading... +
+ ); + + // Log the error to the console, even if redirecting + if (error) { + console.error('Error loading prizes:', error.message); + return null; // Return null since the redirect will occur + } return (

- Список подарков + {data.data.title}

Поздравляю с победой в викторине! Вы стали победителем и получаете возможность выбрать @@ -49,9 +65,9 @@ const PrizesPage = ({ params }: { params: { user_id: string } }) => { Есть вопросы? Обратись XYXYXY!

-
- {data.length > 0 && - data.map((prize, i) => ( +
+ {data.data.gifts && + data.data.gifts.map((prize, i) => ( { : 'disabled' } setSelectedPrize={setSelectedPrize} - prizeId={prize.id} + id={prize.id} + code={params.user_id} + {...prize} /> ))}
diff --git a/components/prizes/PrizeCard.tsx b/components/prizes/PrizeCard.tsx index fafec6a..149f80b 100644 --- a/components/prizes/PrizeCard.tsx +++ b/components/prizes/PrizeCard.tsx @@ -10,53 +10,98 @@ import { DialogTitle, DialogTrigger, } from '@/components/ui/dialog'; -import { Button } from 'react-day-picker'; -import { Dispatch, SetStateAction } from 'react'; -import { ClassNames } from '@emotion/react'; +import { Dispatch, SetStateAction, useState } from 'react'; +import axios from 'axios'; +import { useMutation } from '@tanstack/react-query'; interface IProps { variant: 'default' | 'selected' | 'disabled'; - prizeId: number; setSelectedPrize: Dispatch>; className?: string; + code: string; + title: string; + description: string; + image: null | string; + id: number; } -const PrizeCard = ({ variant, prizeId, setSelectedPrize, className }: IProps) => { +const PrizeCard = ({ + variant, + setSelectedPrize, + code, + id, + title, + description, + image, + className, +}: IProps) => { + const [dialogOpen, setDialogOpen] = useState(false); + const [dialogTitle, setDialogTitle] = useState('Успешно'); + + // TanStack Query mutation for the API request + const choosePrizeMutation = useMutation({ + mutationFn: () => + axios.post(`https://sms.turkmentv.gov.tm/api/gifts/${id}/choose`, { + code, + }), + onSuccess: () => { + // Set the selected prize on successful API request + setSelectedPrize(id); + setDialogTitle('Успешно'); + setDialogOpen(true); // Open the dialog on success + }, + onError: () => { + // Set the dialog title to "Ошибка" on error + setDialogTitle('Ошибка'); + setDialogOpen(true); // Open the dialog on error + }, + }); + + const handleDialogTriggerClick = () => { + choosePrizeMutation.mutate(); + }; + return (
- prize + prize

- Новый Cadillac Escalade 2025 Premium Luxury Platinun + {title}

- Это роскошный полноразмерный SUV, представленный американским производителем Cadillac. - Этот автомобиль отличается высоким уровнем комфорта, стиля и технологий.{' '} + {description}

{variant === 'default' ? ( - - - Выбрать + + + {choosePrizeMutation.isLoading ? 'Loading...' : 'Выбрать'} - Успешно! + {dialogTitle} Все прошло успешно! - diff --git a/components/prizes/SmsForm.tsx b/components/prizes/SmsForm.tsx index 0f8b273..45c7ca6 100644 --- a/components/prizes/SmsForm.tsx +++ b/components/prizes/SmsForm.tsx @@ -4,11 +4,9 @@ import React, { useState, useEffect, FormEvent } from 'react'; import axios from 'axios'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useRouter } from 'next/navigation'; +import { GiftsType } from '@/typings/gifts/gifts.type'; // Define the expected shape of the API response -interface GiftResponse { - data: any; // Replace 'any' with the actual data type if known -} const SmsForm: React.FC = () => { const [inputValue, setInputValue] = useState(''); @@ -17,7 +15,7 @@ const SmsForm: React.FC = () => { const router = useRouter(); // TanStack Query mutation for the API request - const mutation = useMutation({ + const mutation = useMutation({ mutationKey: [`gifts-${inputValue}`], // Using the dynamic query key mutationFn: (code: string) => axios.get(`https://sms.turkmentv.gov.tm/api/gifts/${code}`), onSuccess: (data) => { diff --git a/typings/gifts/gifts.type.ts b/typings/gifts/gifts.type.ts new file mode 100644 index 0000000..6485227 --- /dev/null +++ b/typings/gifts/gifts.type.ts @@ -0,0 +1,10 @@ +export interface GiftsType { + data: Data; +} + +export interface Data { + id: number; + title: string; + image: null; + gifts: any[]; +}