From 620df555f2cce6e182ca0c6316d27a710eac1fbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=A5=98=EC=A0=95=EC=9A=B0?= Date: Tue, 17 Dec 2024 17:20:03 +0900 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20random=20quiz=20swiper=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(routes)/quiz/random/page.tsx | 20 +++- src/features/category/config/index.ts | 22 ++--- .../collection/components/collection.tsx | 3 +- .../components/create-collection-form.tsx | 8 +- .../quiz/screen/random-quiz-view/index.tsx | 96 ++++++++----------- src/requests/collection/server.ts | 11 +++ src/requests/directory/client.tsx | 2 +- src/requests/directory/hooks.ts | 4 +- src/requests/directory/server.ts | 19 ++++ 9 files changed, 106 insertions(+), 79 deletions(-) create mode 100644 src/requests/directory/server.ts diff --git a/src/app/(routes)/quiz/random/page.tsx b/src/app/(routes)/quiz/random/page.tsx index e93a8b98..94bd11d4 100644 --- a/src/app/(routes)/quiz/random/page.tsx +++ b/src/app/(routes)/quiz/random/page.tsx @@ -1,10 +1,24 @@ import RandomQuizView from '@/features/quiz/screen/random-quiz-view' -import { getBookmarkedCollections } from '@/requests/collection/server' +import { getBookmarkedCollections, getMyCollections } from '@/requests/collection/server' +import { getDirectories } from '@/requests/directory/server' const RandomQuiz = async () => { - const bookmarkedCollections = await getBookmarkedCollections() + const [bookmarkedCollections, myCollections, directories] = await Promise.all([ + getBookmarkedCollections(), + getMyCollections(), + getDirectories(), + ]) - return + const directoriesHasDocuments = directories.directories.filter( + (directory) => directory.documentCount > 0 + ) + + return ( + + ) } export default RandomQuiz diff --git a/src/features/category/config/index.ts b/src/features/category/config/index.ts index fa362ae4..8a69c6e5 100644 --- a/src/features/category/config/index.ts +++ b/src/features/category/config/index.ts @@ -1,57 +1,57 @@ type Category = { - code: Collection.Field + id: Collection.Field name: string emoji: string } export const CATEGORIES: Category[] = [ { - code: 'IT', + id: 'IT', name: 'IT·프로그래밍', emoji: '🤖', }, { - code: 'LAW', + id: 'LAW', name: '법률·정치', emoji: '📖', }, { - code: 'BUSINESS_ECONOMY', + id: 'BUSINESS_ECONOMY', name: '경제·경영', emoji: '💰', }, { - code: 'SOCIETY_POLITICS', + id: 'SOCIETY_POLITICS', name: '사회·정치', emoji: '⚖️', }, { - code: 'LANGUAGE', + id: 'LANGUAGE', name: '언어', emoji: '💬', }, { - code: 'MEDICINE_PHARMACY', + id: 'MEDICINE_PHARMACY', name: '의학·약학', emoji: '🩺', }, { - code: 'ART', + id: 'ART', name: '예술', emoji: '🎨', }, { - code: 'SCIENCE_ENGINEERING', + id: 'SCIENCE_ENGINEERING', name: '과학·공학', emoji: '🔬', }, { - code: 'HISTORY_PHILOSOPHY', + id: 'HISTORY_PHILOSOPHY', name: '역사·철학', emoji: '📜', }, { - code: 'OTHER', + id: 'OTHER', name: '기타', emoji: '♾️', }, diff --git a/src/features/collection/components/collection.tsx b/src/features/collection/components/collection.tsx index 73c45a50..667c55ef 100644 --- a/src/features/collection/components/collection.tsx +++ b/src/features/collection/components/collection.tsx @@ -34,8 +34,7 @@ const Collection = ({ }: Props) => { const { mutate: bookmarkMutate } = useBookmarkMutation() - const categoryLabel = - CATEGORIES.find((categoryItem) => categoryItem.code === category)?.name ?? '' + const categoryLabel = CATEGORIES.find((categoryItem) => categoryItem.id === category)?.name ?? '' return (
diff --git a/src/features/collection/components/create-collection-form.tsx b/src/features/collection/components/create-collection-form.tsx index 6f2eff69..68e5aa68 100644 --- a/src/features/collection/components/create-collection-form.tsx +++ b/src/features/collection/components/create-collection-form.tsx @@ -51,7 +51,7 @@ const CreateCollectionForm = () => { const [emoji, setEmoji] = useState('🥹') const [title, setTitle] = useState('') const [description, setDescription] = useState('') - const [categoryCode, setCategoryCode] = useState(CATEGORIES[0]?.code ?? 'IT') + const [categoryCode, setCategoryCode] = useState(CATEGORIES[0]?.id ?? 'IT') const { data: directoryQuizzesData, isLoading: directoryQuizzesLoading } = useDirectoryQuizzes(selectedDirectoryId) @@ -225,7 +225,7 @@ const CreateCollectionForm = () => {
category.code === categoryCode)?.name ?? ''} + title={CATEGORIES.find((category) => category.id === categoryCode)?.name ?? ''} />
@@ -235,10 +235,10 @@ const CreateCollectionForm = () => {
{CATEGORIES.map((category) => ( - + setCategoryCode(category.code)} + onClick={() => setCategoryCode(category.id)} /> ))} diff --git a/src/features/quiz/screen/random-quiz-view/index.tsx b/src/features/quiz/screen/random-quiz-view/index.tsx index 701e9a30..f68b0720 100644 --- a/src/features/quiz/screen/random-quiz-view/index.tsx +++ b/src/features/quiz/screen/random-quiz-view/index.tsx @@ -3,7 +3,7 @@ import { Swiper, SwiperSlide } from 'swiper/react' import 'swiper/css' -import { useMemo, useState } from 'react' +import { useLayoutEffect, useMemo, useRef, useState } from 'react' import { cn } from '@/shared/lib/utils' import './style.css' @@ -19,10 +19,12 @@ import Tag from '@/shared/components/ui/tag' import QuizOptions from '../quiz-view/components/quiz-option' import { CATEGORIES } from '@/features/category/config' import { notFound } from 'next/navigation' +import { components } from '@/types/schema' +import { DeepRequired } from 'react-hook-form' interface Props { - collections: Collection.Response.GetBookmarkedCollections['collections'] - directories: Directory.Response.GetDirectories['directories'] + collections: DeepRequired[] + directories: DeepRequired[] } type CategoryWithQuizzesAndCollectionName = { @@ -31,11 +33,6 @@ type CategoryWithQuizzesAndCollectionName = { } const RandomQuizView = ({ collections, directories }: Props) => { - const [categoriesWithQuizzes, setCategoriesWithQuizzes] = useState([]) - const [] = useState() - - // 디렉토리에 생성된 모든 랜덤 퀴즈 가져옴 - const randomQuizList = [...quizzes] // 임시 const [repository, setRepository] = useState<'directory' | 'collection'>('directory') @@ -43,10 +40,13 @@ const RandomQuizView = ({ collections, directories }: Props) => { const [activeCategoryIndex, setActiveCategoryIndex] = useState(0) const activeDirectoryId = useMemo( - () => mockDirectories[activeDirectoryIndex]?.id, - [activeDirectoryIndex] + () => directories[activeDirectoryIndex]?.id, + [activeDirectoryIndex, directories] + ) + const activeCategoryCode = useMemo( + () => CATEGORIES[activeCategoryIndex]?.id, + [activeCategoryIndex] ) - const activeCategoryCode = 1 const [openExplanation, setOpenExplanation] = useState(false) @@ -110,6 +110,23 @@ const RandomQuizView = ({ collections, directories }: Props) => { undefined > + const [SwiperContainerWidth, setSwiperContainerWidth] = useState(0) + const swiperContainerRef = useRef(null) + useLayoutEffect(() => { + if (swiperContainerRef.current) { + setSwiperContainerWidth(swiperContainerRef.current.clientWidth) + } + const handleResize = () => { + if (swiperContainerRef.current) { + setSwiperContainerWidth(swiperContainerRef.current.clientWidth) + } + } + window.addEventListener('resize', handleResize) + return () => window.removeEventListener('resize', handleResize) + }, []) + + const slideItems = repository === 'directory' ? directories : CATEGORIES + if (!currentQuiz) { notFound() } @@ -171,10 +188,11 @@ const RandomQuizView = ({ collections, directories }: Props) => {
{/* Swiper 영역 */} -
+
{ initialSlide={repository === 'directory' ? activeDirectoryIndex : activeCategoryIndex} onSlideChange={(data) => handleSlideChange(data.activeIndex)} > - {mockDirectories.map((item, index) => { + {slideItems.map((item, index) => { const isActive = repository === 'directory' ? index === activeDirectoryIndex @@ -191,9 +209,13 @@ const RandomQuizView = ({ collections, directories }: Props) => { return ( - @@ -219,17 +241,17 @@ const RandomQuizView = ({ collections, directories }: Props) => { export default RandomQuizView -interface CategoryItemProps { +interface SlideItemProps { isActive: boolean data: { - id: number + id: number | string name: string emoji: string } variant: 'directory' | 'collection' } -const CategoryItem = ({ isActive, data, variant }: CategoryItemProps) => { +const SlideItem = ({ isActive, data, variant }: SlideItemProps) => { const styles = { directory: { background: { @@ -277,41 +299,3 @@ const CategoryItem = ({ isActive, data, variant }: CategoryItemProps) => {
) } - -const mockDirectories = [ - { - id: 1, - name: '파이썬기본문법과응용', - emoji: '❄️', - }, - { - id: 2, - name: '통계학이론', - emoji: '🌱', - }, - { - id: 3, - name: '제테크상식', - emoji: '💵', - }, - { - id: 4, - name: '전공 공부', - emoji: '🔥', - }, - { - id: 5, - name: '세계사 1급', - emoji: '🌍', - }, - { - id: 6, - name: '강의 복기', - emoji: '✏️', - }, - { - id: 7, - name: '통계학이론', - emoji: '🌂', - }, -] diff --git a/src/requests/collection/server.ts b/src/requests/collection/server.ts index 951a8c2c..094fc8ce 100644 --- a/src/requests/collection/server.ts +++ b/src/requests/collection/server.ts @@ -25,3 +25,14 @@ export const getBookmarkedCollections = async () => { throw error } } + +export const getMyCollections = async () => { + try { + const { data } = await httpServer.get( + API_ENDPOINTS.COLLECTION.GET.MY_COLLECTIONS + ) + return data + } catch (error) { + throw error + } +} diff --git a/src/requests/directory/client.tsx b/src/requests/directory/client.tsx index 9034393e..62604f9f 100644 --- a/src/requests/directory/client.tsx +++ b/src/requests/directory/client.tsx @@ -6,7 +6,7 @@ import { http } from '@/shared/lib/axios/http' /** * 모든 디렉토리 가져오기 */ -export const fetchDirectories = async () => { +export const getDirectories = async () => { try { const { data } = await http.get( API_ENDPOINTS.DIRECTORY.GET.ALL diff --git a/src/requests/directory/hooks.ts b/src/requests/directory/hooks.ts index 6218ec47..91ae15ba 100644 --- a/src/requests/directory/hooks.ts +++ b/src/requests/directory/hooks.ts @@ -4,7 +4,7 @@ import { useMutation, useQuery } from '@tanstack/react-query' import { createDirectory, deleteDirectory, - fetchDirectories, + getDirectories, fetchDirectory, updateDirectoryInfo, } from './client' @@ -17,7 +17,7 @@ import { queries } from '@/shared/lib/tanstack-query/query-keys' export const useDirectories = () => { return useQuery({ queryKey: ['directories'], - queryFn: async () => fetchDirectories(), + queryFn: async () => getDirectories(), }) } diff --git a/src/requests/directory/server.ts b/src/requests/directory/server.ts new file mode 100644 index 00000000..aaf3f854 --- /dev/null +++ b/src/requests/directory/server.ts @@ -0,0 +1,19 @@ +'use server' + +import { API_ENDPOINTS } from '@/shared/configs/endpoint' +import { httpServer } from '@/shared/lib/axios/http-server' + +/** + * 모든 디렉토리 가져오기 + */ +export const getDirectories = async () => { + try { + const { data } = await httpServer.get( + API_ENDPOINTS.DIRECTORY.GET.ALL + ) + return data + } catch (error: unknown) { + console.error(error) + throw error + } +} From 778a6729111b45b3637a007cad21c7b05d79f506 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=A5=98=EC=A0=95=EC=9A=B0?= Date: Sat, 21 Dec 2024 19:37:39 +0900 Subject: [PATCH 2/3] feat: random quiz --- src/app/(routes)/quiz/random/page.tsx | 14 +- .../quiz-view/components/quiz-option.tsx | 4 +- .../quiz/screen/random-quiz-view/index.tsx | 124 +++++++++++------- src/features/quiz/utils/index.ts | 8 +- src/requests/collection/client.ts | 11 ++ src/requests/collection/hooks.ts | 9 ++ src/requests/quiz/hooks.ts | 2 +- src/shared/configs/endpoint.ts | 2 + src/types/collection.d.ts | 7 + src/types/quiz.d.ts | 18 +++ 10 files changed, 133 insertions(+), 66 deletions(-) diff --git a/src/app/(routes)/quiz/random/page.tsx b/src/app/(routes)/quiz/random/page.tsx index 94bd11d4..db166b93 100644 --- a/src/app/(routes)/quiz/random/page.tsx +++ b/src/app/(routes)/quiz/random/page.tsx @@ -1,24 +1,14 @@ import RandomQuizView from '@/features/quiz/screen/random-quiz-view' -import { getBookmarkedCollections, getMyCollections } from '@/requests/collection/server' import { getDirectories } from '@/requests/directory/server' const RandomQuiz = async () => { - const [bookmarkedCollections, myCollections, directories] = await Promise.all([ - getBookmarkedCollections(), - getMyCollections(), - getDirectories(), - ]) + const directories = await getDirectories() const directoriesHasDocuments = directories.directories.filter( (directory) => directory.documentCount > 0 ) - return ( - - ) + return } export default RandomQuiz diff --git a/src/features/quiz/screen/quiz-view/components/quiz-option.tsx b/src/features/quiz/screen/quiz-view/components/quiz-option.tsx index 40b1bc2a..b50e155f 100644 --- a/src/features/quiz/screen/quiz-view/components/quiz-option.tsx +++ b/src/features/quiz/screen/quiz-view/components/quiz-option.tsx @@ -6,7 +6,7 @@ import { QUIZ_ANIMATION_DURATION } from '@/features/quiz/config' import { cn } from '@/shared/lib/utils' interface QuizOptionsProps { - quiz: Quiz.Item + quiz: Quiz.Item | Quiz.RandomItem currentResult: Quiz.Result | null onAnswer: (params: { id: number; isRight: boolean; choseAnswer: string }) => void className?: HTMLElement['className'] @@ -31,7 +31,7 @@ const QuizOptions = ({ quiz, currentResult, onAnswer, className }: QuizOptionsPr if (quiz.quizType === 'MULTIPLE_CHOICE') { return ( [] directories: DeepRequired[] } -type CategoryWithQuizzesAndCollectionName = { - category: (typeof CATEGORIES)[number] - quizzes: (Quiz.Item & { tag: string })[] -} - -const RandomQuizView = ({ collections, directories }: Props) => { - const randomQuizList = [...quizzes] // 임시 +const RandomQuizView = ({ directories }: Props) => { + const router = useRouter() + const [randomQuizList, setRandomQuizList] = useState([]) const [repository, setRepository] = useState<'directory' | 'collection'>('directory') const [activeDirectoryIndex, setActiveDirectoryIndex] = useState(0) const [activeCategoryIndex, setActiveCategoryIndex] = useState(0) @@ -43,9 +39,18 @@ const RandomQuizView = ({ collections, directories }: Props) => { () => directories[activeDirectoryIndex]?.id, [activeDirectoryIndex, directories] ) - const activeCategoryCode = useMemo( - () => CATEGORIES[activeCategoryIndex]?.id, - [activeCategoryIndex] + const activeCategoryId = useMemo(() => CATEGORIES[activeCategoryIndex]?.id, [activeCategoryIndex]) + + const { data: randomCollectionQuizzesData } = useRandomCollectionQuizzes(activeCategoryId) + const randomCollectionQuizzes = useMemo( + () => randomCollectionQuizzesData?.quizzes ?? [], + [randomCollectionQuizzesData?.quizzes] + ) + + const { data: randomDirectoryQuizzesData } = useDirectoryQuizzes(activeDirectoryId) + const randomDirectoryQuizzes = useMemo( + () => randomDirectoryQuizzesData?.quizzes ?? [], + [randomDirectoryQuizzesData?.quizzes] ) const [openExplanation, setOpenExplanation] = useState(false) @@ -127,9 +132,22 @@ const RandomQuizView = ({ collections, directories }: Props) => { const slideItems = repository === 'directory' ? directories : CATEGORIES - if (!currentQuiz) { - notFound() - } + useEffect(() => { + if (repository === 'directory') { + setRandomQuizList(randomDirectoryQuizzes) + } else { + setRandomQuizList(randomCollectionQuizzes) + } + router.replace('/quiz/random') + setQuizResults([]) + }, [ + router, + repository, + randomCollectionQuizzes, + randomDirectoryQuizzes, + setRandomQuizList, + setQuizResults, + ]) return (
@@ -149,26 +167,32 @@ const RandomQuizView = ({ collections, directories }: Props) => {
{/* 문제 영역 */} -
- - {currentQuiz.document.name} - - - - {currentQuiz.question} - - - -
+ {currentQuiz ? ( +
+ + + {currentQuiz.document?.name || currentQuiz.collection?.name} + + + + + {currentQuiz.question} + + + +
+ ) : ( + + )} {/* 탭 영역 */} { emoji: item.emoji, }} variant={repository === 'directory' ? 'directory' : 'collection'} + quizCount={randomQuizList.length} /> ) @@ -229,10 +254,10 @@ const RandomQuizView = ({ collections, directories }: Props) => {
@@ -249,9 +274,10 @@ interface SlideItemProps { emoji: string } variant: 'directory' | 'collection' + quizCount: number } -const SlideItem = ({ isActive, data, variant }: SlideItemProps) => { +const SlideItem = ({ isActive, data, variant, quizCount }: SlideItemProps) => { const styles = { directory: { background: { @@ -277,9 +303,13 @@ const SlideItem = ({ isActive, data, variant }: SlideItemProps) => {
@@ -289,9 +319,9 @@ const SlideItem = ({ isActive, data, variant }: SlideItemProps) => { > {data.name} - {isActive && ( + {isActive && quizCount > 0 && ( - 232문제 + {quizCount}문제 )}
diff --git a/src/features/quiz/utils/index.ts b/src/features/quiz/utils/index.ts index 95cc79ff..4b1dae1e 100644 --- a/src/features/quiz/utils/index.ts +++ b/src/features/quiz/utils/index.ts @@ -4,16 +4,16 @@ export const getOptionCondition = ( rightAnswer: string ) => { if (!isQuizSolved(result)) return 'IDLE' - if (result.answer === true && result.choseAnswer === option) return 'RIGHT' - if (result.answer === false && result.choseAnswer === option) return 'WRONG' + if (result?.answer === true && result?.choseAnswer === option) return 'RIGHT' + if (result?.answer === false && result?.choseAnswer === option) return 'WRONG' if (option === rightAnswer) return 'RIGHT' return 'DISABLED' } export const getOXCondition = (result: Quiz.Result | null) => { if (!isQuizSolved(result)) return 'IDLE' - if (result.answer === true && result.choseAnswer === 'correct') return 'RIGHT' - if (result.answer === false && result.choseAnswer === 'correct') return 'WRONG' + if (result?.answer === true && result?.choseAnswer === 'correct') return 'RIGHT' + if (result?.answer === false && result?.choseAnswer === 'correct') return 'WRONG' return 'WRONG' } diff --git a/src/requests/collection/client.ts b/src/requests/collection/client.ts index cde8c45e..640dae4b 100644 --- a/src/requests/collection/client.ts +++ b/src/requests/collection/client.ts @@ -75,3 +75,14 @@ export const getCollectionInfo = async ({ collectionId }: { collectionId: number throw error } } + +export const getRandomCollectionQuizzes = async ({ categoryId }: { categoryId: string }) => { + try { + const { data } = await http.get( + API_ENDPOINTS.COLLECTION.GET.RANDOM_QUIZZES(categoryId) + ) + return data + } catch (error) { + throw error + } +} diff --git a/src/requests/collection/hooks.ts b/src/requests/collection/hooks.ts index 77f22e47..efb6c994 100644 --- a/src/requests/collection/hooks.ts +++ b/src/requests/collection/hooks.ts @@ -8,6 +8,7 @@ import { createBookmark, getMyCollections, getCollectionInfo, + getRandomCollectionQuizzes, } from './client' export const useCollections = () => { @@ -38,6 +39,14 @@ export const useBookmarkedCollections = () => { }) } +export const useRandomCollectionQuizzes = (categoryId?: string) => { + return useQuery({ + queryKey: ['randomCollectionQuizzes', categoryId], + queryFn: async () => getRandomCollectionQuizzes({ categoryId: categoryId! }), + enabled: categoryId != null, + }) +} + export const useCreateCollection = () => { const queryClient = getQueryClient() diff --git a/src/requests/quiz/hooks.ts b/src/requests/quiz/hooks.ts index 89558d38..18231042 100644 --- a/src/requests/quiz/hooks.ts +++ b/src/requests/quiz/hooks.ts @@ -20,7 +20,7 @@ import { queries } from '@/shared/lib/tanstack-query/query-keys' // }) // } -export const useDirectoryQuizzes = (directoryId: number | null) => { +export const useDirectoryQuizzes = (directoryId?: number) => { return useQuery({ queryKey: ['directoryQuizzes', directoryId], queryFn: async () => fetchDirectoryQuizzes({ directoryId: directoryId! }), diff --git a/src/shared/configs/endpoint.ts b/src/shared/configs/endpoint.ts index a5e407fb..510d83c6 100644 --- a/src/shared/configs/endpoint.ts +++ b/src/shared/configs/endpoint.ts @@ -34,6 +34,8 @@ export const API_ENDPOINTS = { BOOKMARKED: '/collections/bookmarked-collections', /** GET /collections-analysis - 컬렉션 분석 */ ANALYSIS: '/collections-analysis', + /** GET /collections/{collection_category}/quizzes - 북마크하거나 소유한 컬렉션 분야별로 모든 퀴즈 랜덤하게 가져오기 */ + RANDOM_QUIZZES: (categoryId: string) => `/collections/${categoryId}/quizzes`, }, POST: { /** POST /collections - 컬렉션 생성 */ diff --git a/src/types/collection.d.ts b/src/types/collection.d.ts index b109a1ff..ce0c8934 100644 --- a/src/types/collection.d.ts +++ b/src/types/collection.d.ts @@ -102,6 +102,13 @@ declare global { paths['/api/v2/collections-analysis']['get']['responses']['200']['content']['application/json;charset=UTF-8'] > + /** GET /api/v2/collections/{collection_category}/quizzes + * 북마크하거나 소유한 컬렉션 분야별로 모든 퀴즈 랜덤하게 가져오기 + */ + type GetRandomCollectionQuizzes = DeepRequired< + paths['/api/v2/collections/{collection_category}/quizzes']['get']['responses']['200']['content']['application/json;charset=UTF-8'] + > + /** POST /api/v2/collections * 컬렉션 생성 */ diff --git a/src/types/quiz.d.ts b/src/types/quiz.d.ts index 9d2aa420..f5dcff59 100644 --- a/src/types/quiz.d.ts +++ b/src/types/quiz.d.ts @@ -17,6 +17,23 @@ type Metadata = { directory: DeepRequired } +type RandomQuiz = { + id: number + question: string + answer: string + explanation: string + options: string[] + quizType: 'MIX_UP' | 'MULTIPLE_CHOICE' + document?: { + id: number + name: string + } + collection?: { + id: number + name: string + } +} + declare global { /** <참고> * OX : correct/incorrect @@ -25,6 +42,7 @@ declare global { declare namespace Quiz { type Item = QuizItem type ReplayType = ReplayQuizType + type RandomItem = RandomQuiz type Type = QuizType type ReplayType = QuizType | 'RANDOM' From b278453f789c3c959c65fb1622e4af65bc666525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=A5=98=EC=A0=95=EC=9A=B0?= Date: Sat, 21 Dec 2024 19:42:01 +0900 Subject: [PATCH 3/3] feat: infinite random quiz --- .../quiz/screen/random-quiz-view/index.tsx | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/features/quiz/screen/random-quiz-view/index.tsx b/src/features/quiz/screen/random-quiz-view/index.tsx index 2dc8f562..55b22878 100644 --- a/src/features/quiz/screen/random-quiz-view/index.tsx +++ b/src/features/quiz/screen/random-quiz-view/index.tsx @@ -56,11 +56,17 @@ const RandomQuizView = ({ directories }: Props) => { const [openExplanation, setOpenExplanation] = useState(false) const { currentIndex, navigateToNext } = useQuizNavigation() - const { handleNext, quizResults, setQuizResults } = useQuizState({ + const { quizResults, setQuizResults } = useQuizState({ quizCount: randomQuizList.length, currentIndex, }) + const currentQuiz = randomQuizList[currentIndex] + const currentResult = quizResults[currentIndex] as Exclude< + (typeof quizResults)[number], + undefined + > + const handleSlideChange = (index: number) => { if (repository === 'directory') { setActiveDirectoryIndex(index) @@ -74,12 +80,13 @@ const RandomQuizView = ({ directories }: Props) => { setOpenExplanation(false) } - const hasNextQuiz = handleNext(currentIndex, randomQuizList.length) - if (hasNextQuiz) { - navigateToNext(currentIndex) - } else { - // TODO: 종료 로직 추가 + if (repository === 'directory') { + // API 요청 } + + // 무한히 반복되기 위함 + setRandomQuizList((prev) => [...prev, currentQuiz!]) + navigateToNext(currentIndex) } const onAnswer = ({ @@ -109,12 +116,6 @@ const RandomQuizView = ({ directories }: Props) => { } } - const currentQuiz = randomQuizList[currentIndex] - const currentResult = quizResults[currentIndex] as Exclude< - (typeof quizResults)[number], - undefined - > - const [SwiperContainerWidth, setSwiperContainerWidth] = useState(0) const swiperContainerRef = useRef(null) useLayoutEffect(() => {