I am new to react and am creating a simple laundry management system. I have written the front end code using React. The full App.js code is below:
import React, { useState, useEffect } from 'react';
function AdminInterface()
{
const [registrationNumber, setRegistrationNumber] = useState('');
const [studentData, setStudentData] = useState(null);
// Function to fetch student data by registration number from the backend
const fetchStudentData = async () => {
try
{
const response = await fetch(`http://localhost:4000/students?student_id=${registrationNumber}`);
if (!response.ok)
{
// Handle HTTP errors
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
setStudentData(data); // Set the studentData state with the fetched data
}
catch (error)
{
// Handle network issues or other errors
console.error('Error fetching student data:', error);
throw error;
}
};
useEffect(() => {
// Fetch student data when the component mounts
if (registrationNumber)
{
fetchStudentData();
}
}, [registrationNumber]);
return (
<div>
<h1>Admin Interface</h1>
<input
type="text"
placeholder="Enter Registration Number"
value={registrationNumber}
onChange={(e) => setRegistrationNumber(e.target.value)}
/>
<button onClick={fetchStudentData}>Get Student Data</button>
{studentData && (
<div>
{/* Display student data here */}
<p>Name: {studentData.name}</p>
<p>Student ID: {studentData.student_id}</p>
<p>Washes Remaining: {studentData.number_of_washes_remaining}</p>
</div>
)}
</div>
);
}
export default AdminInterface;
I have also written the back end for this using express and MongoDB. The server.js code is given below:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
// MongoDB Connection
mongoose.connect('mongodb://localhost/laundryDB', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => console.log('Connected to MongoDB'));
// Middleware
app.use(bodyParser.json());
app.use(cors());
// Define the schema for the Students collection
const studentSchema = new mongoose.Schema({
name: String,
student_id: String,
number_of_washes_remaining: Number,
});
// Create the model for the Students collection
const Student = mongoose.model('Student', studentSchema);
// Define the schema for the Laundry bags collection
const laundryBagSchema = new mongoose.Schema({
student_id: String,
number_of_washes: Number,
time_submitted: Date,
});
// Create the model for the Laundry bags collection
const LaundryBag = mongoose.model('LaundryBag', laundryBagSchema);
// Define the schema for the QR codes collection
const qrCodeSchema = new mongoose.Schema({
student_id: String,
qr_code: String,
});
// Create the model for the QR codes collection
const QRCode = mongoose.model('QRCode', qrCodeSchema);
app.post('/students', async (req, res) => {
try
{
// Implement student registration logic
const { name, student_id } = req.body;
const newStudent = new Student({ name, student_id, number_of_washes_remaining: 4 });
const savedStudent = await newStudent.save();
res.status(201).json(savedStudent);
}
catch (error)
{
res.status(500).json({ error: 'Unable to register student' });
}
});
app.put('/laundrybags/:id', async (req, res) => {
try
{
// Implement laundry bag update logic
const laundryBagId = req.params.id;
const { status } = req.body; // 'completed', 'in progress', or 'waiting'
// Find and update the laundry bag with the specified ID
const updatedLaundryBag = await LaundryBag.findByIdAndUpdate(
laundryBagId,
{ status },
{ new: true } // Return the updated document
);
if (!updatedLaundryBag)
{
res.status(404).json({ error: 'Laundry bag not found' });
}
else
{
res.json(updatedLaundryBag);
}
}
catch (error)
{
res.status(500).json({ error: 'Unable to update laundry bag' });
}
});
app.put('/students/:id', async (req, res) => {
try
{
// Implement wash count modification logic
const studentId = req.params.id;
const { washesRemaining } = req.body;
// Find and update the student's wash count
const updatedStudent = await Student.findByIdAndUpdate(
studentId,
{ number_of_washes_remaining: washesRemaining },
{ new: true } // Return the updated document
);
if (!updatedStudent)
{
res.status(404).json({ error: 'Student not found' });
}
else
{
res.json(updatedStudent);
}
}
catch (error)
{
res.status(500).json({ error: 'Unable to modify wash count' });
}
});
app.get('/students/:id/bill', async (req, res) => {
try
{
// Implement bill calculation logic
const studentId = req.params.id;
// Find the student by ID
const student = await Student.findById(studentId);
if (!student)
{
res.status(404).json({ error: 'Student not found' });
return;
}
// Calculate the bill based on the number of washes
const bill = calculateBill(student.number_of_washes_remaining);
res.json({ bill });
}
catch (error)
{
res.status(500).json({ error: 'Unable to calculate the bill' });
}
});
function calculateBill(washesRemaining)
{
return washesRemaining * 5;
}
// Start the server
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
The entire thing is running on localhost. The node server is running on port 4000 while the front end is running on port 3000.The mongoDB server is also up and running. These are the success messages for each of them:
server.js:
(node:64191) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
(Use `node --trace-warnings ...` to show where the warning was created)
(node:64191) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Server is running on port 4000
Connected to MongoDB
App.js:
Compiled with warnings.
[eslint]
src/App.js
Line 37:6: React Hook useEffect has a missing dependency: 'fetchStudentData'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
WARNING in [eslint]
src/App.js
Line 37:6: React Hook useEffect has a missing dependency: 'fetchStudentData'. Either include it or remove the dependency array react-hooks/exhaustive-deps
webpack compiled with 1 warning
When I try to change the port to 4000 in the below line from App.js, I get the error below the code.
const response = await fetch(`http://localhost:4000/students?student_id=${registrationNumber}`);
The error:
Uncaught runtime errors:
×
ERROR
HTTP error! Status: 404
at fetchStudentData (http://localhost:3000/main.21f8a2fd0db6306edf18.hot-update.js:35:15)
However, if I change it to 3000, the application runs and I see the textbox and button. But every time I type any character at all in the text box, I get the error:
bundle.js:45 Error fetching student data: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
fetchStudentData @ bundle.js:45
await in fetchStudentData (async)
(anonymous) @ bundle.js:52
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
commitRootImpl @ react-dom.development.js:26935
commitRoot @ react-dom.development.js:26682
performSyncWorkOnRoot @ react-dom.development.js:26117
flushSyncCallbacks @ react-dom.development.js:12042
flushSync @ react-dom.development.js:26201
finishEventHandler @ react-dom.development.js:3976
batchedUpdates @ react-dom.development.js:3994
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Regarding the MongoDB, this is a document I added to the students collection manually:
[
{
_id: ObjectId("654510f7eb83799d03397996"),
name: 'S SS',
student_id: '20BCE7388',
number_of_washes_remaining: 4
}
]
Could you please let me know what the problem with my code is so that I can solve? Would be helpful if you could tell me how to solve the issue as well.