Quiz App using MERN Stack
Last Updated :
23 Jul, 2025
In this article, we’ll walk through the step-by-step process of creating a complete quiz application with MongoDB, ReactJS, ExpressJS, and NodeJS. This application will provide users with a user-friendly interface for taking and submitting quizzes and a scoreboard to check their standing among others.

Prerequisites:
Approach to Create a Quiz App with MERN Stack:
Backend:
- Set up a new NodeJS project with npm or yarn and initialize a Git repository.
- Use dotenv to manage environment variables. Set up MongoDB Atlas for cloud hosting. Configure environment variables for MongoDB connection URI and application port. Install Express, Mongoose, and cors.
- Create a new express application and set up middleware. Define API routes for handling data requests. Implement CRUD operations for questions and results data.
- Define MongoDB schemas for Question and Result models. Create Mongoose models to interact with the MongoDB database.
- Implement controller functions for handling business logic. Interact with the MongoDB database using the Mongoose models and return responses to clients.
- Configure the application to listen on the defined port. Start the server. Use nodemon for automatic server restarts during development.
React Frontend:
- Set up a new React project with create-react-app. Initialize a Git repository. Define the project structure.
- Install react-router-dom for client-side routing. Set up routes for pages/component
- Install redux, react-redux, and redux-thunk. Define actions, reducers, and the store for state management.
- Use Axios or Fetch API to fetch data from backend endpoints. Implement logic for loading, error, and success states during data fetching.
- Define UI components for rendering the quiz questions, results, and other elements. Use Bootstrap or CSS frameworks for styling.
- Implement functionalities like starting the quiz, answering questions, navigating, and displaying results. Handle user input, form submission, and button clicks.
Steps to Create the Backend Server:
Step 1: Create a directory for the project.
mkdir server
cd server
Step 2: Initialized the Express app and installing the required packages
npm init -y
Step 3: Install the necessary package in your server using the following command.
npm i express mongoose cors dotenv mongoose morgan nodemon
Project Structure:
Backend Folder StructureThe updated dependencies in package.json file of backend will look like:
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"mongoose": "^8.2.0",
"morgan": "^1.10.0",
"nodemon": "^3.1.0"
}
Example: Create the required files and write the following code.
JavaScript
// server.js
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import { config } from 'dotenv';
import router from './router/route.js';
import connect from './database/conn.js';
config();
const app = express();
app.use(morgan('tiny'));
app.use(cors());
app.use(express.json());
const port = process.env.PORT || 8080;
app.use('/api', router);
app.get('/', (req, res) => {
try {
res.json("Get Request")
} catch (error) {
res.json(error)
}
});
connect().then(() => {
app.listen(port, () => {
console.log(`Server connected to http://localhost:${port}`);
});
}).catch(error => {
console.log("Invalid Database Connection");
});
JavaScript
//database/conn.js
import mongoose from "mongoose";
export default async function connect(){
try {
await mongoose.connect(process.env.ATLAS_URI);
console.log("Database Connected");
} catch (error) {
console.log("Invalid Database Connection");
}
}
JavaScript
//database/data.js
export default [
{
id: 1,
question : "Javascript is an _______ language",
options : [
'Object-Oriented',
'Object-Based',
'Procedural',
]
},
{
id: 2,
question : "Following methods can be used to display data in some form using Javascript",
options : [
'document.write()',
'console.log()',
'window.alert()',
]
},
{
id: 3,
question : "When an operator value is NULL, the typeof returned by the unary operator is:",
options : [
'Boolean',
'Undefined',
'Object',
]
},
{
id: 4,
question : "What does the toString() method return?",
options : [
'Return Object',
'Return String',
'Return Integer'
]
},
{
id: 5,
question : "Which function is used to serialize an object into a JSON string?",
options : [
'stringify()',
'parse()',
'convert()',
]
}
];
export const answers = [0, 1, 2, 1, 0];
JavaScript
//models/questionSchema.js
import mongoose from "mongoose";
const { Schema } = mongoose;
/** question model */
const questionModel = new Schema({
questions: { type : Array, default: []}, // create question with [] default value
answers : { type : Array, default: []},
createdAt: { type: Date, default: Date.now },
});
export default mongoose.model('Question', questionModel);
JavaScript
//models/resultSchema.js
import mongoose from "mongoose";
const { Schema } = mongoose;
/** result model */
const resultModel = new Schema({
username : { type : String },
result : { type : Array, default : []},
attempts : { type : Number, default : 0},
points : { type : Number, default : 0},
achived : { type : String, default : ''},
createdAt : { type : Date, default : Date.now}
})
export default mongoose.model('result', resultModel);
JavaScript
//router/router.js
import { Router } from "express";
import * as controller from '../controllers/controller.js';
const router = Router();
router.route('/')
router.route('/questions')
.get(controller.getQuestions)
.post(controller.insertQuestions)
.delete(controller.dropQuestions);
router.route('/result')
.get(controller.getResult)
.post(controller.storeResult)
.delete(controller.dropResult);
export default router;
JavaScript
//controller/controller.js
import Questions from "../models/questionSchema.js";
import Results from "../models/resultSchema.js";
import questions, { answers } from '../database/data.js'
/** get all questions */
export async function getQuestions(req, res) {
try {
let q = await Questions.find();
if (q.length === 0) {
await Questions.insertMany({ questions, answers });
q = await Questions.find();
}
res.json(q);
} catch (error) {
res.json({ error });
}
}
/** insert all questinos */
export async function insertQuestions(req, res) {
try {
Questions.insertMany({ questions: questions, answers: answers })
} catch (error) {
res.json({ error })
}
}
/** Delete all Questions */
export async function dropQuestions(req, res) {
try {
await Questions.deleteMany();
res.json({ msg: "Questions Deleted Successfully...!" });
} catch (error) {
res.json({ error })
}
}
/** get all result */
export async function getResult(req, res) {
try {
const r = await Results.find();
res.json(r)
} catch (error) {
res.json({ error })
}
}
/** post all result */
export async function storeResult(req, res) {
try {
const { username, result, attempts, points, achived } = req.body;
if (!username && !result) throw new Error('Data Not Provided...!');
const newResult = await Results.create({ username, result, attempts, points, achived });
res.json({ msg: "Result Saved Successfully...!", result: newResult });
} catch (error) {
res.json({ error });
}
}
/** delete all result */
export async function dropResult(req, res) {
try {
await Results.deleteMany();
res.json({ msg: "Result Deleted Successfully...!" })
} catch (error) {
res.json({ error })
}
}
Steps to Setup Frontend with React
Step 1: Create React App
npx create-react-app client
Step 2: Switch to the project directory
cd client
Step 3: Installing the required packages:
npm install react-redux react-router-dom axios nodemon @reduxjs/toolkit
Step 4: Create a folder inside the src folder i.e. components, helper, hooks, and redux. Inside component create App.js, Main.js, Question.js, Quiz.js, Result.js, ResultTable.js. Inside helper create helper.js, in the hooks folder create FetchQuestion.js, setResult.js and inside the redux folder create question_reducer.js, result_reducer.js, store.js.
Project Structure:
Frontend Folder StructureThe updated dependency in package.json file of frontend will look like:
"dependencies": {
"@reduxjs/toolkit": "^2.2.1",
"axios": "^1.6.7",
"nodemon": "^3.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-router-dom": "^6.22.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: Create the required files and write the following code.
CSS
/* styles/App.css */
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
:root {
--primary-color: #0DFF92;
--dark-color: #222222;
--light-color: #f0f0f0;
}
body,
html {
height: 100%;
background: var(--dark-color)
}
*>* {
font-family: 'Poppins', sans-serif;
}
.container {
display: block;
position: relative;
margin: 40px auto;
height: auto;
width: 800px;
padding: 20px;
}
.container .title {
font-size: 3em;
text-align: center;
border: 5px solid var(--primary-color);
padding: .3em .2em;
border-radius: 4px;
}
.text-light {
color: var(--light-color)
}
.container ul {
list-style: none;
margin: 0;
padding: 0;
overflow: auto;
}
.container .questions {
padding: 3em;
}
/*
.container .questions .qid{
padding: .2em .7em;
color: #222222;
background-color: #0DFF92;
border-radius: 50px;
} */
.container .grid {
margin-top: 3em;
display: grid;
grid-template-columns: 1fr 1fr;
}
.container .btn {
padding: .2em 1.7em;
border: none;
border-radius: .1em;
font-size: 1.2em;
}
.container .btn:hover {
cursor: pointer;
background-color: #f0f0f0;
color: #202020;
}
.next {
background-color: var(--primary-color);
justify-self: flex-end;
}
.prev {
background-color: #faff5a;
justify-self: flex-start;
}
ul li {
color: #AAAAAA;
display: block;
position: relative;
float: left;
width: 100%;
height: 100px;
border-bottom: 1px solid #333;
}
ul li input[type=radio] {
position: absolute;
visibility: hidden;
}
ul li label {
display: block;
position: relative;
font-weight: 300;
font-size: 1.35em;
padding: 25px 25px 25px 80px;
margin: 10px auto;
height: 30px;
z-index: 9;
cursor: pointer;
-webkit-transition: all 0.25s linear;
}
ul li:hover label {
color: #FFFFFF;
}
ul li .check {
display: block;
position: absolute;
border: 5px solid #AAAAAA;
border-radius: 100%;
height: 25px;
width: 25px;
top: 30px;
left: 20px;
z-index: 5;
transition: border .25s linear;
-webkit-transition: border .25s linear;
}
ul li:hover .checked {
border: 5px solid #FFFFFF;
}
ul li .check::before {
display: block;
position: absolute;
content: '';
border-radius: 100%;
height: 15px;
width: 15px;
top: 5px;
left: 5px;
margin: auto;
transition: background 0.25s linear;
-webkit-transition: background 0.25s linear;
}
input[type=radio]:checked~.check {
border: 5px solid var(--primary-color)
}
input[type=radio]:checked~.check::before {
background: var(--primary-color)
}
input[type=radio]:checked~.text-primary {
color: var(--primary-color)
}
/* To get selected option we are using this checked class */
.checked {
border: 5px solid var(--primary-color) !important;
}
.checked::before {
background: var(--primary-color)
}
CSS
/* styles/index.css */
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
CSS
/* styles/Main.css */
.container ol li {
font-size: 1.4em;
color: #cecece;
}
.start {
display: flex;
justify-content: center;
padding-top: 2em;
}
.start .btn {
padding: .2em 1.7em;
border: none;
border-radius: .1em;
font-size: 1.2em;
color: #202020;
text-decoration: none;
background-color: #faff5a;
}
#form {
display: flex;
justify-content: center;
margin-top: 4em;
}
#form .userid {
padding: .7em 2em;
width: 50%;
border: none;
border-radius: 3px;
font-size: 1em;
}
CSS
/* styles/Result.css */
.flex-center {
display: flex;
justify-content: center;
flex-direction: column;
border: 1px solid #cecece;
padding: 3em 4em;
gap: 1em;
}
.container .flex {
display: flex;
justify-content: space-between;
}
.container .flex span {
font-size: 1.4em;
color: #cecece;
}
.container .flex span.achive {
font-weight: bold;
color: #ff2a66;
color: #2aff95;
}
table {
width: 100%;
}
.table-header {
color: #cecece;
font-size: 1.1em;
text-align: center;
background: #212121;
padding: 18px 0;
}
.table-body {
font-size: 1.1em;
text-align: center;
/* color: #cecece; */
background: #d8d8d8;
padding: 18px 0;
}
.table-header>tr>td {
border: 1px solid #faff5a;
}
JavaScript
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './styles/index.css';
import App from './components/App';
/** Redux Store */
import store from './redux/store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
JavaScript
//components/App.js
import '../styles/App.css';
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
/** import components */
import Main from './Main';
import Quiz from './Quiz';
import Result from './Result';
import { CheckUserExist } from '../helper/helper';
/** react routes */
const router = createBrowserRouter([
{
path: '/',
element: <Main></Main>
},
{
path: '/quiz',
element: <CheckUserExist><Quiz /></CheckUserExist>
},
{
path: '/result',
element: <CheckUserExist><Result /></CheckUserExist>
},
])
function App() {
return (
<>
<RouterProvider router={router} />
</>
);
}
export default App;
JavaScript
//components/Main.js
import React, { useRef } from "react";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import { setUserId } from "../redux/result_reducer";
import "../styles/Main.css";
export default function Main() {
const inputRef = useRef(null);
const dispatch = useDispatch();
function startQuiz() {
if (inputRef.current?.value) {
dispatch(setUserId(inputRef.current?.value));
}
}
return (
<div className="container">
<h1 className="title text-light">Quiz Application</h1>
<ol>
<li>You will be asked 10 questions one after another.</li>
<li>10 points is awarded for the correct answer.</li>
<li>
Each question has three options. You can choose only one options.
</li>
<li>You can review and change answers before the quiz finish.</li>
<li>The result will be declared at the end of the quiz.</li>
</ol>
<form id="form">
<input
ref={inputRef}
className="userid"
type="text"
placeholder="Username*"
/>
</form>
<div className="start">
<Link className="btn" to={"quiz"} onClick={startQuiz}>
Start Quiz
</Link>
</div>
</div>
);
}
JavaScript
//components/Questions.js
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useFetchQestion } from "../hooks/FetchQuestion";
import { updateResult } from "../hooks/setResult";
export default function Questions({ onChecked }) {
const dispatch = useDispatch();
const { trace } = useSelector((state) => state.questions);
const result = useSelector((state) => state.result.result);
const [{ isLoading, apiData, serverError }] = useFetchQestion();
const questions = useSelector((state) => state.questions.queue[trace]);
function onSelect(i) {
dispatch(updateResult({ trace, checked: i }));
onChecked(i); // Call the parent handler to update parent state
}
if (isLoading) return <h3 className="text-light">Loading...</h3>;
if (serverError)
return <h3 className="text-light">{serverError || "Unknown Error"}</h3>;
if (!questions) return <h3 className="text-light">No questions available</h3>;
return (
<div className="questions">
<h2 className="text-light">{questions?.question}</h2>
<ul key={questions?.id}>
{questions?.options.map((q, i) => (
<li key={i}>
<input
type="radio"
value={i}
name={`options-${questions.id}`}
id={`q${i}-option`}
onChange={() => onSelect(i)}
checked={result[trace] === i}
/>
<label className="text-primary" htmlFor={`q${i}-option`}>
{q}
</label>
<div
className={`check ${result[trace] === i ? "checked" : ""}`}
></div>
</li>
))}
</ul>
</div>
);
}
JavaScript
//components/Quiz.js
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Navigate } from "react-router-dom";
import Questions from "./Questions";
import { MoveNextQuestion, MovePrevQuestion } from "../hooks/FetchQuestion";
import { PushAnswer } from "../hooks/setResult";
export default function Quiz() {
const [check, setChecked] = useState(undefined);
const result = useSelector((state) => state.result.result);
const { queue, trace } = useSelector((state) => state.questions);
const dispatch = useDispatch();
function onNext() {
if (trace < queue.length) {
dispatch(MoveNextQuestion());
if (result.length <= trace) {
dispatch(PushAnswer(check));
}
}
setChecked(undefined);
}
function onPrev() {
if (trace > 0) {
dispatch(MovePrevQuestion());
}
}
function onChecked(check) {
setChecked(check);
}
if (result.length && result.length >= queue.length) {
return <Navigate to={"/result"} replace={true}></Navigate>;
}
return (
<div className="container">
<h1 className="title text-light">Quiz Application</h1>
<Questions onChecked={onChecked} />
<div className="grid">
{trace > 0 ? (
<button className="btn prev" onClick={onPrev}>
Prev
</button>
) : (
<div></div>
)}
<button className="btn next" onClick={onNext}>
Next
</button>
</div>
</div>
);
}
JavaScript
//components/Result.js
import React, { useEffect } from "react";
import "../styles/Result.css";
import { Link } from "react-router-dom";
import ResultTable from "./ResultTable";
import { useDispatch, useSelector } from "react-redux";
import {
attempts_Number,
earnPoints_Number,
flagResult,
} from "../helper/helper";
/** import actions */
import { resetAllAction } from "../redux/question_reducer";
import { resetResultAction } from "../redux/result_reducer";
import { usePublishResult } from "../hooks/setResult";
export default function Result() {
const dispatch = useDispatch();
const {
questions: { queue, answers },
result: { result, userId },
} = useSelector((state) => state);
const totalPoints = queue.length * 10;
const attempts = attempts_Number(result);
const earnPoints = earnPoints_Number(result, answers, 10);
const flag = flagResult(totalPoints, earnPoints);
/** store user result */
usePublishResult({
result,
username: userId,
attempts,
points: earnPoints,
achived: flag ? "Passed" : "Failed",
});
function onRestart() {
dispatch(resetAllAction());
dispatch(resetResultAction());
}
return (
<div className="container">
<h1 className="title text-light">Quiz Application</h1>
<div className="result flex-center">
<div className="flex">
<span>Username</span>
<span className="bold">{userId || ""}</span>
</div>
<div className="flex">
<span>Total Quiz Points : </span>
<span className="bold">{totalPoints || 0}</span>
</div>
<div className="flex">
<span>Total Questions : </span>
<span className="bold">{queue.length || 0}</span>
</div>
<div className="flex">
<span>Total Attempts : </span>
<span className="bold">{attempts || 0}</span>
</div>
<div className="flex">
<span>Total Earn Points : </span>
<span className="bold">{earnPoints || 0}</span>
</div>
<div className="flex">
<span>Quiz Result</span>
<span
style={{ color: `${flag ? "#2aff95" : "#ff2a66"}` }}
className="bold"
>
{flag ? "Passed" : "Failed"}
</span>
</div>
</div>
<div className="start">
<Link className="btn" to={"/"} onClick={onRestart}>
Restart
</Link>
</div>
<div className="container">
{/* result table */}
<ResultTable></ResultTable>
</div>
</div>
);
}
JavaScript
//components/ResultTable.js
import React, { useEffect, useState } from 'react';
import { getServerData } from '../helper/helper';
export default function ResultTable() {
const [data, setData] = useState([]);
useEffect(() => {
getServerData(`http://localhost:${process.env.PORT || 5000}/api/result`, (res) => {
setData(res);
}).catch(error => console.error('Error fetching result data:', error));
}, []);
if (!data || data.length === 0) return <div>No Data Found</div>;
return (
<div>
<table>
<thead className='table-header'>
<tr className='table-row'>
<td>Name</td>
<td>Attempts</td>
<td>Earn Points</td>
<td>Result</td>
</tr>
</thead>
<tbody>
{data.map((v, i) => (
<tr className='table-body' key={i}>
<td>{v?.username || ''}</td>
<td>{v?.attempts || 0}</td>
<td>{v?.points || 0}</td>
<td>{v?.achieved || ''}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
JavaScript
//helper/helper.js
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import axios from "axios";
export function attempts_Number(result) {
return result.filter((r) => r !== undefined).length;
}
export function earnPoints_Number(result, answers, point) {
return result
.map((element, i) => answers[i] === element)
.filter((i) => i)
.map((i) => point)
.reduce((prev, curr) => prev + curr, 0);
}
export function flagResult(totalPoints, earnPoints) {
return (totalPoints * 50) / 100 < earnPoints; /** earn 50% marks */
}
/** check user auth */
export function CheckUserExist({ children }) {
const auth = useSelector((state) => state.result.userId);
return auth ? children : <Navigate to={"/"} replace={true}></Navigate>;
}
/** get server data */
export async function getServerData(url, callback) {
const data = await (await axios.get(url))?.data;
return callback ? callback(data) : data;
}
/** post server data */
export async function postServerData(url, result, callback) {
const data = await (await axios.post(url, result))?.data;
return callback ? callback(data) : data;
}
JavaScript
//hooks/setResult.js
import { postServerData } from "../helper/helper";
import * as Action from "../redux/result_reducer";
export const PushAnswer = (result) => async (dispatch) => {
try {
await dispatch(Action.pushResultAction(result));
} catch (error) {
console.error("Error pushing answer:", error);
}
};
export const updateResult = (payload) => async (dispatch) => {
try {
dispatch(Action.updateResultAction(payload));
} catch (error) {
console.error("Error updating result:", error);
}
};
/** insert user data */
export const usePublishResult = (resultData) => {
const { result, username } = resultData;
(async () => {
try {
if (!result.length || !username) {
throw new Error("Couldn't get Result: Invalid result or username.");
}
const port = process.env.PORT || 5000;
const response = await postServerData(
`http://localhost:${port}/api/result`,
resultData
);
console.log("Result published:", response);
} catch (error) {
console.error("Error publishing result:", error);
}
})();
};
JavaScript
//redux/question_reducer.js
import { createSlice } from "@reduxjs/toolkit";
/** create reducer */
export const questionReducer = createSlice({
name: "questions",
initialState: {
queue: [],
answers: [],
trace: 0,
},
reducers: {
startExamAction: (state, action) => {
let { question, answers } = action.payload;
return {
...state,
queue: question,
answers,
};
},
moveNextAction: (state) => {
return {
...state,
trace: state.trace + 1,
};
},
movePrevAction: (state) => {
return {
...state,
trace: state.trace - 1,
};
},
resetAllAction: () => {
return {
queue: [],
answers: [],
trace: 0,
};
},
},
});
export const {
startExamAction,
moveNextAction,
movePrevAction,
resetAllAction,
} = questionReducer.actions;
export default questionReducer.reducer;
JavaScript
//redux/result_rducer.js
import { createSlice } from "@reduxjs/toolkit";
export const resultReducer = createSlice({
name: "result",
initialState: {
userId: null,
result: [],
},
reducers: {
setUserId: (state, action) => {
state.userId = action.payload;
},
pushResultAction: (state, action) => {
state.result.push(action.payload);
},
updateResultAction: (state, action) => {
const { trace, checked } = action.payload;
state.result[trace] = checked;
},
resetResultAction: () => {
return {
userId: null,
result: [],
};
},
},
});
export const {
setUserId,
pushResultAction,
resetResultAction,
updateResultAction,
} = resultReducer.actions;
export default resultReducer.reducer;
JavaScript
//redux/store.js
import { combineReducers, configureStore } from "@reduxjs/toolkit";
/** call reducers */
import questionReducer from "./question_reducer";
import resultReducer from "./result_reducer";
const rootReducer = combineReducers({
questions: questionReducer,
result: resultReducer,
});
/** create store with reducer */
export default configureStore({ reducer: rootReducer });
JavaScript
//hooks/FetchQuestions.js
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { getServerData } from "../helper/helper";
import * as Action from "../redux/question_reducer";
/** fetch question hook to fetch api data and set value to store */
export const useFetchQestion = () => {
const dispatch = useDispatch();
const [getData, setGetData] = useState({
isLoading: false,
apiData: [],
serverError: null,
});
useEffect(() => {
setGetData((prev) => ({ ...prev, isLoading: true }));
/** async function fetch backend data */
(async () => {
try {
const [{ questions, answers }] = await getServerData(
`http://localhost:${process.env.PORT || 5000}/api/questions`,
(data) => data
);
if (questions.length > 0) {
setGetData((prev) => ({ ...prev, isLoading: false }));
setGetData((prev) => ({ ...prev, apiData: questions }));
/** dispatch an action */
dispatch(Action.startExamAction({ question: questions, answers }));
} else {
throw new Error("No Question Available");
}
} catch (error) {
setGetData((prev) => ({ ...prev, isLoading: false }));
setGetData((prev) => ({ ...prev, serverError: error.message }));
}
})();
}, [dispatch]);
return [getData, setGetData];
};
/** MoveAction Dispatch function */
export const MoveNextQuestion = () => (dispatch) => {
try {
dispatch(Action.moveNextAction()); /** increase trace by 1 */
} catch (error) {
console.error("Error moving to next question:", error);
}
};
/** PrevAction Dispatch function */
export const MovePrevQuestion = () => (dispatch) => {
try {
dispatch(Action.movePrevAction()); /** decrease trace by 1 */
} catch (error) {
console.error("Error moving to previous question:", error);
}
};
Steps to run the App:
node server.js
npm start
Output:
Similar Reads
MERN Stack The MERN stack is a widely adopted full-stack development framework that simplifies the creation of modern web applications. Using JavaScript for both the frontend and backend enables developers to efficiently build robust, scalable, and dynamic applications.What is MERN Stack?MERN Stack is a JavaSc
9 min read
MERN Full Form MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications. The full form of MERN includes four powerful technologies:MongoDBExpress.jsReact.jsNode.jsThese technologies together provide a full-stack JavaScript framework for developing modern, dynami
2 min read
How to Become a MERN Stack Developer? Do you also get amazed at those beautiful websites that appear in front of you? Those are designed by none other than Full-Stack Developers Or MERN stack developers. They are software developers who specialize in building web applications using the MERN stack, which is a popular set of technologies
6 min read
Difference between MEAN Stack and MERN Stack Web development is a procedure or process for developing a website. A website basically contains three ends: the client side, the server side, and the database. These three are different sides of an application that combine together to deliver an application; all ends are implemented separately with
3 min read
Best Hosting Platforms for MERN Projects Hosting your website grants you the thrilling opportunity to showcase it to the world. Whether you choose free or paid hosting, the process of deploying your website fills you with a mix of excitement, pride, and nervousness. You eagerly await user feedback, enthusiastically embracing the chance to
5 min read
Getting Started with React & Frontend
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Props - Set 1The react props refer to properties in react that are passed down from parent component to child to render the dynamic content.Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component.What are Prop
5 min read
ReactJS StateIn React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
Create ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list allows users to add new tasks and delete them by clicking the corresponding
3 min read
Redux Setup and basics
Introduction to Redux (Action, Reducers and Store)Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.Uses: It makes easier to manage state and data. As the complexity of our application in
4 min read
Redux and The Flux ArchitectureFlux Architecture: Flux is AN architecture that Facebook uses internally when operating with React. It is not a framework or a library. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow. Redux is a predictable state container for JavaS
5 min read
React Redux Hooks: useSelector and useDispatch.State management is a major aspect of building React applications, allowing users to maintain and update application state predictably. With the introduction of React Hooks, managing state has become even more streamlined and efficient. Among the most commonly used hooks for state management in Reac
4 min read
What are Action's creators in React Redux?In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects.Action C
4 min read
What is Redux Thunk?Redux Thunk is like a co-worker for Redux, giving it the power to handle asynchronous actions. It's that extra tool that allows your Redux store to deal with things like fetching data from a server or performing tasks that take some time. With Redux Thunk, your app can smoothly manage both synchrono
3 min read
Creating custom middlewares in React ReduxIn React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
5 min read
Common middleware libraries used in ReduxMiddleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
5 min read
Express and Mongo Setup
Mongo with Express TutorialMongoDB and ExpressJS are a powerful pair for web development. MongoDB provides flexible data storage, while ExpressJS simplifies server-side logic. Together, they make it easy to create modern web applications efficiently. MongoDB's document-based approach and ExpressJS's streamlined backend develo
5 min read
How to Install MongoDB on Windows?Looking to install MongoDB on your Windows machine? This detailed guide will help you install MongoDB on Windows (Windows Server 2022, 2019, and Windows 11) quickly and efficiently. Whether you are a developer or a beginner, follow this guide for seamless MongoDB installation, including setting up e
6 min read
How to Install Express in a Node Project?ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services.Be
2 min read
Mongoose Module IntroductionMongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and structured way to interact with MongoDB, allowing you to define schemas for your collections, apply constraints, and validate data before storing it in the database. In this guide, we'
5 min read
Mongoose ConnectionsA Mongoose connection is a Node.js module that establishes and manages connections between a Node.js application and a MongoDB database. It optimizes resource utilization, handles connection pooling, and manages errors, facilitating efficient data operations.What is Mongoose Connection?A Mongoose co
6 min read
How to Connect MongoDB with a Node.js Application using MongooseJSMongoose is a powerful MongoDB object modeling library for Node.js enabling you to easily interact between your Node.js app and MongoDB. In this article we are going to explore how you can connect your Node.js app to MongoDB using MongooseJS. You will learn how to create a connection, specify schema
4 min read
Node.js CRUD Operations Using Mongoose and MongoDB AtlasCRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
8 min read
Signup Form Using Node.js and MongoDBInstallations First, we need to include a few packages for our Nodejs application. npm install express --save Express allows us to set up middlewares to respond to HTTP Requests. npm install body-parser --save If you want to read HTTP POST data , you have to use the "body-parser" node module. npm in
3 min read
API Routing and Authentication
Postman- Backend Testing
Introduction to Postman for API DevelopmentPostman: Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development eas
7 min read
Basics of API Testing Using PostmanAPIs(Application Programming Interfaces) are very commonly used in development. Postman is a tool that can be used for API Testing. In this article, we will learn how to do simple API Testing using Postman. Go to your workspace in Postman.Click on the + symbol to open a new tab.Enter the API Endpoin
2 min read
How to use postman for testing express applicationTesting an Express app is very important to ensure its capability and reliability in different use cases. There are many options available like Thunder client, PAW, etc but we will use Postman here for the testing of the Express application. It provides a great user interface and numerous tools whic
3 min read
How to send different types of requests (GET, POST, PUT, DELETE) in Postman.In this article, we are going to learn how can we send different types of requests like GET, POST, PUT, and DELETE in the Postman. Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge betwe
5 min read
How to test GET Method of express with Postman ?The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can't change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In thi
2 min read
How to test POST Method of Express with Postman?The POST method is a crucial aspect of web development, allowing clients to send data to the server for processing. In the context of Express, a popular web framework for Node, using the POST method involves setting up routes to handle incoming data. In this article, we'll explore how to test the PO
2 min read
How to test DELETE Method of Express with Postman ?The DELETE method is an essential part of RESTful web services used to remove specific resources from a server. Whether you are building a simple API or a complex web application, knowing how to use this method effectively is key. Here, we will explore how to Implement the DELETE method in Express.j
3 min read
How to create and write tests for API requests in Postman?Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
3 min read