import Head from "next/head";
import styles from "@/styles/Home.module.css";
import QuestionBox from "@/components/QuestionBox";
import Timer from "@/components/Timer";
import { FaGithubAlt } from "react-icons/fa";
import type { NextApiRequest, NextApiResponse } from "next";
import mysql from "mysql2/promise";
export default function Home({ data }: { data: Data }) {
const time: Date = new Date();
time.setSeconds(time.getSeconds() + 10);
let question: string;
let answers: string[];
let currentIndex: number;
let lastIndex: number;
if (data.questions.length > 0) {
const wrongAnswers: string[] = data.questions.map((item) => item.answer);
const correctAnswer = data.questions[0].correctAnswer;
question = data.questions[0].question;
currentIndex = data.questions[0].id;
lastIndex = data.count[0]["count(question)"];
answers = [correctAnswer, ...wrongAnswers];
} else {
return <h1>404</h1>;
}
return (
<>
<Head>
<title>SG - Quizz</title>
<meta name="description" content="Quizz App" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<div className={styles.description}>
<div>
Reamening time
<Timer expiryTimestamp={time} />
</div>
<div>
<a
target="_blank"
rel="noreferrer noopener"
href="https://github.com/selcukguler0/Quizz-App">
<FaGithubAlt size={30} />
</a>
</div>
</div>
#next.js TypeError: Cannot read properties of undefined (reading 'length') error
2 messages · Page 1 of 1 (latest)
<div className={styles.center}>
<QuestionBox
lastIndex={lastIndex}
currentIndex={currentIndex}
question={question}
answers={answers}
/>
</div>
<footer>
Made with :heart: by{" "}
<a
target="_blank"
rel="noreferrer noopener"
href="https://www.linkedin.com/in/selçukgüler/">
SG
</a>
</footer>
</main>
</>
);
}
type Data = {
questions: Array<{
id: number;
question: string;
correctAnswer: string;
answer: string;
}>;
count: Array<{
"count(question)": number;
}>;
};
export async function getServerSideProps({
req,
res,
resolvedUrl,
}: {
req: NextApiRequest;
res: NextApiResponse;
resolvedUrl: string;
}) {
const idRegex = /(?<=\?quizzId=)[a-zA-Z0-9]+/;
const qRegex = /(?<=&question=)\d+/;
let quizzMatch = resolvedUrl.match(idRegex);
let questionMatch = resolvedUrl.match(qRegex);
if (quizzMatch && questionMatch) {
let quizzId = quizzMatch[0]!;
let questionId = questionMatch[0]!;
const connection = await mysql.createConnection(
String(process.env.DATABASE_URL)
);