Skip to content

Commit

Permalink
feat: add 'fetch options for quiz' method
Browse files Browse the repository at this point in the history
  • Loading branch information
martapanc-resourcify committed Jul 26, 2023
1 parent 554a391 commit 9ae8124
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 62 deletions.
66 changes: 64 additions & 2 deletions src/app/(public)/about/free-time/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import * as React from 'react';

import { shuffleArray } from '@/lib/helper';

import { QuizOption, QuizProps } from '@/components/molecules/RandomFacts/Quiz';
import Books from '@/components/organisms/about-free-time/Books';
import Music from '@/components/organisms/about-free-time/Music';
import Podcasts from '@/components/organisms/about-free-time/Podcasts';
Expand All @@ -9,13 +12,18 @@ import VideoGames from '@/components/organisms/about-free-time/VideoGames';

import { booksQuery } from '@/queries/books';
import { podcastsQuery } from '@/queries/podcasts';
import {
falseRandomFactsQuery,
trueRandomFactsQuery,
} from '@/queries/random-facts';
import { tvSeriesQuery } from '@/queries/tv-series';
import { videoGamesQuery } from '@/queries/video-games';

import { sanityClient } from '../../../../../sanity/lib/client';

import { Book } from '@/types/Book';
import { Podcast } from '@/types/Podcast';
import { RandomFact } from '@/types/RandomFact';
import { TvShow } from '@/types/TvSeries';
import { VideoGame } from '@/types/VideoGame';

Expand All @@ -24,6 +32,13 @@ export const metadata = {
description: 'About page',
};

export enum Option {
A = 'a',
B = 'b',
C = 'c',
D = 'd',
}

const getData = async () => {
const books: Book[] = await sanityClient.fetch(booksQuery);

Expand All @@ -33,16 +48,60 @@ const getData = async () => {

const videoGames: VideoGame[] = await sanityClient.fetch(videoGamesQuery);

const randomFacts: QuizProps = await loadRandomFactsForQuiz();

return {
books,
podcasts,
tvSeries,
videoGames,
randomFacts,
};
};

const loadRandomFactsForQuiz = async () => {
const falseFacts: RandomFact[] = await sanityClient.fetch(
falseRandomFactsQuery
);
const trueFacts: RandomFact[] = await sanityClient.fetch(
trueRandomFactsQuery
);

const oneFalseFact: RandomFact = shuffleArray(falseFacts)[0];
const threeTrueFacts: RandomFact[] = shuffleArray(trueFacts).slice(0, 3);

const options: QuizOption[] = threeTrueFacts.map((fact) => ({
headline: fact.headline,
}));

options.push({
headline: oneFalseFact.headline,
});

const shuffledOptions = shuffleArray(options);

const keys = ['a', 'b', 'c', 'd'];
const preparedOptions: QuizOption[] = [];
for (let i = 0; i < 4; i++) {
preparedOptions.push({
headline: shuffledOptions[i].headline,
key: keys[i],
});
}

const falseOptionKey: string = preparedOptions.find(
(option) => option.headline === oneFalseFact.headline
)!.key!;

return {
options: preparedOptions,
falseOption: falseOptionKey,
};
};

const AboutFreeTimePage = async () => {
const { books, podcasts, tvSeries, videoGames } = await getData();
const { books, podcasts, tvSeries, videoGames, randomFacts } =
await getData();

return (
<main className='min-h-main'>
Expand All @@ -69,7 +128,10 @@ const AboutFreeTimePage = async () => {

<Music />

<RandomFacts />
<RandomFacts
options={randomFacts.options}
falseOption={randomFacts.falseOption}
/>
</div>
</section>
</main>
Expand Down
18 changes: 7 additions & 11 deletions src/components/molecules/RandomFacts/Quiz.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use client';

import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
Expand All @@ -9,21 +11,14 @@ import Button from '@/components/buttons/Button';

const localStorageKey = 'alreadyPlayed';

export enum Option {
A = 'a',
B = 'b',
C = 'c',
D = 'd',
}

export interface QuizOption {
headline: string;
key: Option;
key?: string;
}

export interface QuizProps {
options: QuizOption[];
falseOption: Option;
falseOption?: string;
}

const Quiz = ({ options, falseOption }: QuizProps) => {
Expand All @@ -41,11 +36,12 @@ const Quiz = ({ options, falseOption }: QuizProps) => {
localStorage.setItem(localStorageKey, 'true');

setSubmitted(true);

const answeredRight = falseOption === selectedAnswer;

// eslint-disable-next-line no-console
console.log(submitted && answeredRight ? 'Correct!' : 'Wrong!');
console.log(submitted);
// eslint-disable-next-line no-console
console.log(answeredRight ? 'Correct!' : 'Wrong!');
};

return (
Expand Down
52 changes: 5 additions & 47 deletions src/components/organisms/about-free-time/RandomFacts.tsx
Original file line number Diff line number Diff line change
@@ -1,70 +1,28 @@
'use client';

import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import * as React from 'react';
import { useState } from 'react';

import Button from '@/components/buttons/Button';
import Quiz, { QuizProps } from '@/components/molecules/RandomFacts/Quiz';

const localStorageKey = 'alreadyPlayed';

const RandomFacts = () => {
const [selectedAnswer, setSelectedAnswer] = useState('');
const RandomFacts = ({ options, falseOption }: QuizProps) => {
const [submitted] = useState(false);

const [submitted, setSubmitted] = useState(false);

const [alreadyPlayed, setAlreadyPlayed] = useState(() => {
const [alreadyPlayed] = useState(() => {
const alreadyPlayed = localStorage.getItem(localStorageKey);
return alreadyPlayed ? JSON.parse(alreadyPlayed) : false;
});

const isButtonDisabled = selectedAnswer === '';

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedAnswer(event.target.value);
};

const submitAnswer = () => {
localStorage.setItem(localStorageKey, 'true');

setSubmitted(true);
setAlreadyPlayed(true);
};

return (
<div className='mb-6'>
<div className='mb-6 mt-2 flex'>
<h2>Random facts about me</h2>
</div>

{!submitted && !alreadyPlayed && (
<div className='rounded dark:bg-slate-900'>
<FormControl>
<RadioGroup
aria-labelledby='demo-radio-buttons-group-label'
name='radio-buttons-group'
value={selectedAnswer}
onChange={handleChange}
>
<FormControlLabel value='a' control={<Radio />} label='A' />
<FormControlLabel value='b' control={<Radio />} label='B' />
<FormControlLabel value='c' control={<Radio />} label='C' />
<FormControlLabel value='d' control={<Radio />} label='D' />
</RadioGroup>

<Button
className='shadow-md'
variant='primary'
onClick={submitAnswer}
disabled={isButtonDisabled}
>
Submit
</Button>
</FormControl>
</div>
<Quiz options={options} falseOption={falseOption} />
)}
{submitted && alreadyPlayed && (
<div className='rounded bg-gray-200 p-4'>
Expand Down
9 changes: 9 additions & 0 deletions src/lib/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,12 @@ export function getFromSessionStorage(key: string): string | null {
}
return null;
}

export function shuffleArray<T>(array: T[]): T[] {
const shuffledArray = [...array];
for (let i = shuffledArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
}
return shuffledArray;
}
5 changes: 5 additions & 0 deletions src/pages/api/random-facts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next';

import { shuffleArray } from '@/lib/helper';

import {
falseRandomFactsQuery,
trueRandomFactsQuery,
Expand All @@ -18,9 +20,12 @@ const randomFactsApi = async (req: NextApiRequest, res: NextApiResponse) => {
falseRandomFactsQuery
);

const oneFalseRandomFact: RandomFact = shuffleArray(falseFacts)[0];

res.status(200).json({
true: trueFacts,
false: falseFacts,
oneFalse: oneFalseRandomFact,
});
};

Expand Down
8 changes: 6 additions & 2 deletions src/queries/random-facts.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { groq } from 'next-sanity';

export const trueRandomFactsQuery = groq`
*[_type == "randomFact" && isFactTrue == true] {
*[_type == "randomFact" && isFactTrue == true && name != "Correspondence"]
{
_id,
name,
headline,
description
}`;

export const falseRandomFactsQuery = groq`
*[_type == "randomFact" && isFactTrue == false] {
*[_type == "randomFact" && isFactTrue == false]
{
_id,
name,
headline,
description,
explanation
}`;
Expand Down
1 change: 1 addition & 0 deletions src/types/RandomFact.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export interface RandomFact {
_id: string;
name: string;
headline: string;
description: string;
trueFact: boolean;
explanation: string;
Expand Down

0 comments on commit 9ae8124

Please sign in to comment.