Skip to content

Commit

Permalink
Take quiz and quizservice
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtan2000 committed Aug 15, 2024
1 parent 8f4f23d commit 02f6efb
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 13 deletions.
5 changes: 3 additions & 2 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ NEXT_PUBLIC_IDP_AuthorizeEndpoint = $NEXT_PUBLIC_COGNITO_URL/oauth2/authorize
NEXT_PUBLIC_IDP_Tokendpoint = $NEXT_PUBLIC_COGNITO_URL/oauth2/token
NEXT_PUBLIC_QUEMISTRY_DOMAIN = https://dkraju438qs82.cloudfront.net
NEXT_PUBLIC_RedirectUrl = $NEXT_PUBLIC_QUEMISTRY_DOMAIN/auth/google
NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL= https://b4jba6xq87.execute-api.ap-southeast-1.amazonaws.com/Staging
#NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL= https://b4jba6xq87.execute-api.ap-southeast-1.amazonaws.com/Staging
NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL= http://localhost:80/v1
NEXT_PUBLIC_QUEMISTRY_AUTH_URL = $NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL/auth
NEXT_PUBLIC_QUEMISTRY_QUESTIONS_URL = $NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL/questions
NEXT_PUBLIC_QUEMISTRY_QUESTIONS_URL = http://localhost:80/questions
NEXT_PUBLIC_QUEMISTRY_CLASS_URL = $NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL/class
NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL = $NEXT_PUBLIC_QUEMISTRY_GATEWAY_URL/quizzes
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@ yarn-error.log*
next-env.d.ts
dist/
.idea
.env
.vscode/settings.json
90 changes: 81 additions & 9 deletions app/(main)/quiz/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,51 @@ import { useEffect, useState } from 'react';
import { Quiz } from '@/types';
import { QuizService } from '../../../service/QuizService';
import { Button } from 'primereact/button';
import { QuestionsService } from '@/service/QuestionsService';
import { Questions } from '@/types';
import { TabView, TabPanel } from 'primereact/tabview';
import { Editor, EditorTextChangeEvent } from "primereact/editor";
import { InputSwitch, InputSwitchChangeEvent } from "primereact/inputswitch";
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dialog } from 'primereact/dialog';
import { TreeSelect, TreeSelectSelectionKeysType } from "primereact/treeselect";
import { useRouter } from 'next/navigation';


const QuizPage: React.FC = () => {
const router = useRouter();
const [selectedTopicNodes, setSelectedTopicNodes] = useState<string | TreeSelectSelectionKeysType | TreeSelectSelectionKeysType[] | null>();
const [topicNodes, setTopicNodes] = useState<any>(null);

const [data, setData] = useState<Quiz.ApiResponse | null>(null);
const [selectedOptions, setSelectedOptions] = useState<{ [key: number]: number | null }>({});
const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(0);
const [isDisabled, setIsDisabled] = useState(false);


const [addedOptions, setAddedOptions] = useState<Questions.Option[]>([]);
const [stem, setStem] = useState<string>('');
const [answer, setAnswer] = useState<string>('');
const [explanation, setExplanation] = useState<string>('');
const [isAnswer, setIsAnswer] = useState<boolean>(false);
const [listOfTopics, setListOfTopics] = useState<Questions.Topic[]>([]);
const [showOptionDialog, setShowOptionDialog] = useState<boolean>(false);

const [activeTab, setActiveTab] = useState<number>(0);


useEffect(() => {
const fetchData = async () => {
try {
const responseData = await QuizService.fetchData();
const responseData = await QuizService.getQuizInProgress();
setData(responseData);

// Initialize selectedOptions with keys for each mcq.id set to null
console.log('responseData.message', responseData.message)
if (responseData.message === 'Quiz not found') {
setData(null);
return;
}
// Initialize selectedOptions with keys for each mcq.id set to null
const initialSelectedOptions: { [key: number]: number | null } = {};
responseData.mcqs.forEach((mcq) => {
initialSelectedOptions[mcq.id] = null;
Expand All @@ -37,12 +69,14 @@ const QuizPage: React.FC = () => {
}
};

if (!data) {
return <div>Loading...</div>;
var currentQuestion = false;
try {
currentQuestion = data.mcqs[currentQuestionIndex];

} catch (error) {
console.log('Error, try to start a quiz?');
}

const currentQuestion = data.mcqs[currentQuestionIndex];

const handleNextQuestion = () => {
if (currentQuestionIndex < data.mcqs.length - 1) {
setCurrentQuestionIndex(currentQuestionIndex + 1);
Expand All @@ -54,12 +88,50 @@ const QuizPage: React.FC = () => {
<div className="col-12">
<div className="card">
<h5>Quizzes</h5>
<p>You currently have an ongoing quiz.</p>
{!data && (
<div className="flex flex-wrap gap-2">
<Button label="Resume Quiz" onClick={() => window.location.reload()}></Button>
<h5>Take Quiz</h5>
<br/>
<TabView activeIndex={activeTab} onTabChange={(e) => setActiveTab(e.index)}>
<TabPanel header="General Information">
<div className="grid">
<div className="col-12 md:col-12 mb-5">
<TreeSelect value={selectedTopicNodes} onChange={(e)=> setSelectedTopicNodes(e.value)} options={topicNodes}
className="md:w-50rem w-full" metaKeySelection={false} selectionMode="checkbox" display="chip" placeholder="Select Topics / Skills"
showClear></TreeSelect>
</div>
<div className="col-12 md:col-12 mb-5">
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }} className="col-12">
<Button label="Next" onClick={()=> {setActiveTab(1)}}></Button>
</div>
</div>
</TabPanel>
<TabPanel header="Options">
<div className="grid">
<div className="col-12 md:col-12 mb-5">
<p>Default question count will be two.</p>
</div>
<div className="col-12 md:col-12 mb-5">
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }} className="col-12">
<Button label="Next" onClick={()=> {setActiveTab(1)}}></Button>
</div>
</div>
</TabPanel>
</TabView>
<Button onClick={() => { setIsDisabled(true);QuizService.startNewQuiz([2]);setTimeout(()=>{window.location.reload();},1500) } }
disabled={isDisabled}>
{isDisabled ? 'Reloading Page...' : 'Start a new Quiz'}
</Button>
</div>
)}
{/* {!data && (
<div className="flex flex-wrap gap-2">
<p>You currently have an ongoing quiz.</p>
<Button label="Resume Quiz" onClick={() => window.location.reload()}></Button>
</div>
)} */}
{currentQuestion && (
<div key={currentQuestion.id}>
<div className="card">
Expand Down
30 changes: 28 additions & 2 deletions service/QuizService.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
import { Quiz } from '@/types';

export const QuizService = {
fetchData: async (): Promise<Quiz.ApiResponse> => {
startNewQuiz: async (topics: number[]): Promise<Quiz.ApiResponse> => {
try {
console.log('Fetching data from API...');
const response = await fetch(`${process.env.NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-user-id': '12asd',
},
credentials: 'include',
body: JSON.stringify({
topics: topics,
skills: null,
totalSize: 60,
pageSize: 60,
}),
});
const responseData: Quiz.ApiResponse = await response.json();
console.log('Data fetched successfully:', responseData);
return responseData;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
},

getQuizInProgress: async (): Promise<Quiz.ApiResponse> => {
try {
console.log('Fetching data from API...');
const response = await fetch(
`${process.env.NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL}/2?pageNumber=0&pageSize=60`,
`${process.env.NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL}/me/in-progress?pageNumber=0&pageSize=60`,
{
headers: {
'x-user-id': '12asd',
Expand Down

0 comments on commit 02f6efb

Please sign in to comment.