I’m working on a React application designed to manage door access requests within a university environment. The application consists of two main components: RequestLoading and Inbox.
RequestLoading Component:
This component is responsible for displaying a loading indicator while door access requests are being processed. Once a request is approved, it should immediately redirect the user (faculty member) to the GenerateCode page, where a unique access code is generated for the approved request.
Inbox Component:
The Inbox component serves as the interface for managing door access requests. It displays a list of pending requests, allowing the user (administrative staff) to approve or reject them. Upon approval, the request status is updated, and an event is triggered to notify the faculty member and generate an access code.
The problem arises when attempting to redirect the faculty member to the GenerateCode page after approving a request. Despite successfully approving the request, the redirection to the GenerateCode page only occurs after multiple clicks on the “Approve Request” button, which is not the expected behavior. Ideally, the redirection should happen with just one click on the “Approve Request” button, providing a seamless user experience.
RequestForm.jsx
// RequestForm.jsx
import React, { useState } from 'react';
import axios from 'axios';
import { useLocation, useNavigate } from 'react-router-dom';
import './RequestForm.css';
const RequestForm = () => {
const location = useLocation();
const navigate = useNavigate();
const userId = location.state ? location.state.userId : null;
const [formData, setFormData] = useState({
lab_no: '',
date: '',
subject: '',
section: '',
startTime: '',
endTime: '',
message: '',
user_id: userId
});
const handleSubmit = async (event) => {
event.preventDefault();
try {
console.log('Form Data:', formData);
navigate('/request-loading'); // Navigate to the loading page before the request
const response = await axios.post('http://localhost:8081/request-form', formData);
console.log('Server Response:', response.data);
setFormData({
lab_no: '',
date: '',
subject: '',
section: '',
startTime: '',
endTime: '',
message: '',
user_id: userId
});
alert('Request submitted successfully. You will be notified shortly.');
} catch (error) {
console.error('Error:', error);
// Handle the error here, you may want to navigate back to the form or show an error message
}
};
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
return (
<div className='request-main-content'>
<div className='wrapper'>
<div className='request-header'>
<header className='center-text'>Request Access</header>
</div>
<form onSubmit={handleSubmit}>
<div className='details'>
<div className="input-field">
<label>Lab No.</label><br />
<select name="lab_no" value={formData.lab_no} onChange={handleChange} required>
<option disabled value="">--Select an option--</option>
<option value="1">CLAB 1</option>
<option value="2">CLAB 2</option>
<option value="3">CLAB 3</option>
<option value="4">CLAB 4</option>
<option value="5">CLAB 5</option>
<option value="6">CLAB 6</option>
</select>
</div>
<div className="input-field">
<label>Subject</label><br />
<input type='text' name="subject" value={formData.subject} onChange={handleChange} placeholder='Enter Subject' required />
</div>
</div>
<div className="details">
<div className="input-field">
<label>Section</label><br />
<input type='text' name="section" value={formData.section} onChange={handleChange} placeholder='Enter Section' required />
</div>
<div className="input-field">
<label>Date</label><br />
<input type='date' name="date" value={formData.date} onChange={handleChange} required />
</div>
</div>
<div className="details">
<div className="input-field">
<label>Time</label><br />
<div className='time'>
<input type='time' name="startTime" value={formData.startTime} onChange={handleChange} required />
<span>to</span>
<input type='time' name="endTime" value={formData.endTime} onChange={handleChange} required />
</div>
</div>
</div>
<div className="input-field-box">
<label>Message</label><br />
<input type='text' name="message" value={formData.message} onChange={handleChange} placeholder='Send your message here...' required />
</div>
<button type="submit">Submit</button>
</form>
</div>
</div>
);
};
export default RequestForm;
RequestLoading.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import { useNavigate } from 'react-router-dom';
import './Loading.css'; // Assuming Loading.css contains styles for the loading indicator
const socket = io('http://localhost:8081');
const RequestLoading = () => {
const navigate = useNavigate();
const [doorAccessRequests, setDoorAccessRequests] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [isRequestApproved, setIsRequestApproved] = useState(false);
const [notification, setNotification] = useState("");
const [approvedRequestId, setApprovedRequestId] = useState(null);
useEffect(() => {
let isMounted = true; // Flag to track if component is mounted
const fetchDoorAccessRequests = async () => {
try {
const response = await axios.get('http://localhost:8081/door-access-requests');
if (isMounted) {
setDoorAccessRequests(response.data);
setIsLoading(false);
if (response.data.some(request => request.status === 'approved')) {
setIsRequestApproved(true);
}
}
} catch (error) {
console.error('Error fetching door access requests:', error);
setIsLoading(false);
}
};
fetchDoorAccessRequests();
socket.on('request-approved', ({ requestId, code }) => {
setApprovedRequestId(requestId);
if (approvedRequestId === requestId) {
setIsRequestApproved(true);
setTimeout(() => {
if (isMounted) {
navigate('/generate-code', { state: { code } });
}
}, 10); // Adjust the delay as needed
}
});
return () => {
isMounted = false; // Cleanup function to update the flag when component unmounts
socket.off('request-approved');
};
}, [navigate, approvedRequestId]);
const handleApproveAndGenerateCode = async (requestId) => {
const request = doorAccessRequests.find(req => req.id === requestId);
if (request.status === 'approved') {
return;
}
try {
const response = await axios.post(`http://localhost:8081/approve-request/${requestId}`);
const code = response.data.code; // Assuming the API returns the code in the response
setApprovedRequestId(requestId);
setIsRequestApproved(true);
setNotification("Request submitted successfully. You will be notified shortly.");
navigate('/generate-code', { state: { code } }); // Redirect to /generate-code immediately
} catch (error) {
console.error('Error approving request:', error);
setNotification("Error approving request. Please try again.");
}
};
if (isLoading || !isRequestApproved) {
return (
<div className='loading-content'>
<div className='center-text'>
<img src="/loginloading.gif" alt="Loading..." style={{ width: '40px', height: '40px', marginBottom: '10px' }} />
<p>Please wait for the status of your request.</p>
</div>
</div>
);
}
if (notification) {
return (
<div className='notification-message'>
<p>{notification}</p>
</div>
);
}
return null;
};
export default RequestLoading;
Inbox.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import './Inbox.css';
import { MdOutlineDashboard } from "react-icons/md";
import { LuInbox } from "react-icons/lu";
import { IoLockOpenOutline } from "react-icons/io5";
import { LuComputer } from "react-icons/lu";
import { MdOutlineSwitchAccount } from "react-icons/md";
import { VscSignOut } from "react-icons/vsc";
import { HiOutlineMenu } from "react-icons/hi";
import { MdOutlineRefresh } from "react-icons/md";
import { AiOutlineDelete } from "react-icons/ai";
import { FiInbox } from "react-icons/fi";
const socket = io('http://localhost:8081');
const Inbox = () => {
const [sidebarOpen, setSidebarOpen] = useState(false);
const [doorAccessRequests, setDoorAccessRequests] = useState([]);
const [expandedRequestId, setExpandedRequestId] = useState(null);
const [selectAllChecked, setSelectAllChecked] = useState(false);
const [approvedRequestId, setApprovedRequestId] = useState(null);
const toggleSidebar = () => {
setSidebarOpen(!sidebarOpen);
};
useEffect(() => {
const fetchDoorAccessRequests = async () => {
try {
const response = await axios.get('http://localhost:8081/door-access-requests');
setDoorAccessRequests(response.data);
} catch (error) {
console.error('Error fetching door access requests:', error);
}
};
fetchDoorAccessRequests();
socket.on('request-approved', ({ requestId, code }) => {
setApprovedRequestId(requestId);
});
return () => {
socket.off('request-approved');
};
}, [socket, doorAccessRequests]);
const handleApproveAndGenerateCode = async (requestId) => {
const request = doorAccessRequests.find(req => req.id === requestId);
if (request.status === 'approved') {
return;
}
try {
await axios.post(`http://localhost:8081/approve-request/${requestId}`);
alert('Request approved successfully.');
setDoorAccessRequests(prevRequests =>
prevRequests.map(req =>
req.id === requestId? {...req, status: 'approved' } : req
)
);
// Emit the request-approved event with the approved request ID
socket.emit('request-approved', { requestId, code: 'some-generated-code' });
} catch (error) {
console.error('Error approving request and generating code:', error);
}
};
const toggleRequestDetails = (requestId) => {
setExpandedRequestId(expandedRequestId === requestId ? null : requestId);
};
const handleSelectAllChange = (e) => {
setSelectAllChecked(e.target.checked);
const updatedRequests = doorAccessRequests.map(request => ({
...request,
selected: e.target.checked
}));
setDoorAccessRequests(updatedRequests);
};
const handleCheckboxChange = (requestId) => {
const updatedRequests = doorAccessRequests.map(request => {
if (request.id === requestId) {
return {
...request,
selected: !request.selected
};
}
return request;
});
setDoorAccessRequests(updatedRequests);
setSelectAllChecked(updatedRequests.every(request => request.selected));
};
return (
<div className={`inbox-page ${sidebarOpen ? 'sidebar-open' : ''}`}>
{/* Sidebar */}
<div className={`misso-sidebar ${sidebarOpen ? 'open' : ''}`}>
<h2>MISS Office</h2>
<ul>
<li>
<a href='/misso-dash'>
<MdOutlineDashboard />
<span>Dashboard</span>
</a>
</li>
<li>
<a href='/misso-inbox'>
<LuInbox />
<span>Inbox</span>
</a>
</li>
<li>
<a href='/misso-buttons'>
<IoLockOpenOutline />
<span>Buttons</span>
</a>
</li>
<li>
<a href='#'>
<LuComputer />
<span>Lab Oversight</span>
</a>
</li>
</ul>
<ul className='ul-2'>
<li>
<a href='#'>
<MdOutlineSwitchAccount />
<span>Switch Account</span>
</a>
</li>
<li>
<a href='#'>
<VscSignOut />
<span>Log out</span>
</a>
</li>
</ul>
</div>
{/* Sidebar toggle button (visible on small screens) */}
<button className={`sidebar-toggle-btn ${sidebarOpen ? 'active' : ''}`} onClick={toggleSidebar}>
<HiOutlineMenu />
</button>
<div className='misso-inbox-content'>
<div className='misso-inbox-header'>
<h2>Inbox</h2>
<span><FiInbox /></span>
</div>
<div className='inbox-options'>
<input type='checkbox' id='select-all' checked={selectAllChecked} onChange={handleSelectAllChange} />
<label htmlFor='select-all'>Select All</label>
<button><MdOutlineRefresh /></button>
<button><AiOutlineDelete /></button>
</div>
<div className='inbox-content'>
{doorAccessRequests.slice().reverse().map(request => (
<div key={request.id} className={`request-card ${expandedRequestId === request.id ? 'expanded' : ''}`}>
<div className='inbox-header' onClick={() => toggleRequestDetails(request.id)}>
<div className='inbox-wrapper'>
<input type='checkbox' checked={request.selected} onChange={() => handleCheckboxChange(request.id)} />
<div className='inbox-name-space'>
<p className='inbox-name'>{request.fullname}</p>
</div>
<span className="message-preview">{request.message.slice(0, 100)}...</span>
</div>
<span>{new Date().toLocaleString()}</span>
</div>
<div className='request-details'>
<div className='inbox-wrap1'>
<p><strong>Message:</strong> {request.message}</p>
</div>
<div className='inbox-wrapper'>
<div className='inbox-wrap'>
<p><strong>Lab No:</strong> {request.lab_no}</p>
<p><strong>Date:</strong> {request.date}</p>
<p><strong>Subject:</strong> {request.subject}</p>
</div>
<div className='inbox-wrap'>
<p><strong>Section:</strong> {request.section}</p>
<p><strong>Start Time:</strong> {request.start_time}</p>
<p><strong>End Time:</strong> {request.end_time}</p>
</div>
</div>
<div className='inbox-wrap'>
<button onClick={() => handleApproveAndGenerateCode(request.id)}>Approve Request</button>
<span style={{ margin: '0 1px' }}></span>
<button>X</button>
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
export default Inbox;
jae is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.