Cleaned and structured ReactJS, Redux, authentication, JWT, Axios, Material UI and enterprise UI notes.
Source content preserved and organized| Concept | Purpose |
|---|---|
| Props | Pass data from parent to child components. |
| State | Maintain component-local, changing data. |
| Hooks | Use state and other React features in functional components. |
| Redux | Manage predictable application state. |
| Redux-Saga | Handle asynchronous side effects such as API calls. |
| Axios Interceptor | Attach access tokens and centralize 401/refresh handling. |
| ProtectedRoute | Restrict routes when an access token is absent. |
| DataGrid | Display and manage tabular user data. |
| ConfirmDialog | Require confirmation before destructive actions. |
| Toast | Provide success/error feedback to the user. |
| Role-based UI | Show or hide UI actions according to the user's role. |
ü **latest stable version of ReactJS is 18.3.0** (released in early 2025).
ü React was developed and maintained by the folks at Facebook
ü An open source project with an active developer community
ü Implement Single Page Applications (SPA)
ü Easy to understand for developers with the knowledge of XML/HTML
ü High Performant Apps
ü Easy to test
ü React components are the core building blocks of a React application that represent
how a particular element would be visualized on the User Interface.
ü A component may be responsible for performing a single task
ü A typical React app is a component tree having one root component ("App") and then
a potentially infinite amount of nested child components
ü A React component is a reusable component which can be used over and over again in the UI,but not always we are going to render the same component with same data. Sometimes we have to change the data or content inside a component. That’s why props are introduced in React.
ü Props allow you to pass data from a parent component to a child component
Only changes in props and/or state trigger React to re-render your components and potentially
ü update the DOM in the browser.
ü Props are considered as “immutable”
ü Props are supplied as attribute to components
ü A state in React Component is its own local state, the state cannot be accessed and modified
ü outside the component and can only be used inside the component.
ü React components can be made dynamic by adding state to it.
ü State is used when component needs to change independently of its parent
ü Changes to state also trigger an UI update
ü React component’s state can be updated using setState()
ü *Best practice : *top level components are stateful which keep all interaction logic, manage UI state,and pass the state down to hierarchy to stateless components using props
ü Changing state on a Component will never affect its parent, or its siblings, or any other Component in the application: just its children.
ü The state is often moved up in the Component tree, so that it can be shared between components that need to access it.
ü Unidirectional data flow means that data has one, and only one, way to be
ü transferred to other parts of the application.
ü State is passed to the view and to child components
ü Actions are triggered by the view
ü Actions can update the state
ü The state change is passed to the view and to child components
Hooks are a new addition in React 16.8. e.g. useState, useEffect, useContext, useReducer and many more
They let you use state and other React features without writing a class component.
Don’t call Hooks inside loops, conditions, or nested functions. Only call Hooks at the top level.
Only call Hooks from React functional components
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
It provides a great developer experience, such as live code editing combined with a time traveling debugger.
Actions are payloads of information that send data from your application to your store
They are the only source of information for the store.
You send them to the store using store.dispatch()
The reducer is a pure function that takes the previous state and an action , and returns the next state
Reducers specify how the application's state changes in response to actions sent to the store.
Actions only describe what happened, but don't describe how the application's state changes.
**Memoization in ReactJS** means *caching* the result of a function or a component so that it **doesn’t re-compute unnecessarily** when the same inputs (props, state) are provided again.
This helps improve performance, especially for heavy computations or re-rendering complex components.
In React, you mainly see memoization done using:
jsx
CopyEdit
import React from "react";
const MyComponent = ({ name }) => {
console.log("Rendered:", name);
return \<div>Hello {name}\</div>;
};
export default React.memo(MyComponent);
✅ Now, MyComponent will only re-render if name prop changes.
Used to memoize **a calculated value** inside a component.
jsx
CopyEdit
import React, { useMemo } from "react";
const ExpensiveComponent = ({ num }) => {
const calculatedValue = useMemo(() => {
console.log("Calculating...");
return num \* 1000;
}, [num]);
return \<div>Result: {calculatedValue}\</div>;
};
✅ The expensive calculation (num \* 1000) only happens when num changes.
2. useCallback()
Used to memoize **functions**.
It ensures that the same function instance is reused unless dependencies change.
let arr = [1,2,[3,4,[5,6,[7]]]];
and convert it into a simple, flat array like: [1, 2, 3, 4, 5, 6, 7]
1. Using flat() method (simple and modern way)
let arr = [1,2,[3,4,[5,6,[7]]]];
let flatArr = arr.flat(Infinity); // Infinity flattens any level of nesting
console.log(flatArr);
2. Using recursion (if you want to do it manually)
let arr = [1,2,[3,4,[5,6,[7]]]];
function flatten(array) {
let result = [];
for (let item of array) {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
}
return result;
}
console.log(flatten(arr));
ü **Concurrent Features** (like useTransition, startTransition)
ü **Automatic Batching**
ü **Streaming Server-Side Rendering (SSR) with Suspense**
ü **useId hook** for stable ID generation in hydration
ü Improved support for **React Server Components** (still experimental)
ü Improved **React DevTools** integration
👉 Verify installation:
node -v
npm -v
Open **Command Prompt / PowerShell / VS Code Terminal**:
npx create-react-app react-saga-auth
cd react-saga-auth
npm install redux react-redux redux-saga axios
code .
If code command doesn’t work:
Inside src/, create:
redux/
actions/
reducers/
sagas/
services/
components/
👉 In Windows Explorer:
OR
👉 In terminal:
mkdir src\redux\actions src\redux\reducers src\redux\sagas src\services src\components
Run PowerShell as Admin and execute:
Set-ExecutionPolicy RemoteSigned
If port 3000 is busy:
npm start
It will ask:
Would you like to run on another port? (Y/N)
👉 Press **Y**
Fix by reinstalling:
rm -rf node\_modules
npm install
(On Windows, if rm fails:)
rd /s /q node\_modules
npm install
npm start
👉 App opens at:
http\://localhost:3000
Use this:
email: eve\@reqres.in
password: cityslicka
Install:
👉 [https://git-scm.com/](https://git-scm.com/)
Then right-click → **Git Bash Here**
Create .env in root:
REACT\_APP\_API\_URL=https\://reqres.in/api
Update service:
baseURL: process.env.REACT\_APP\_API\_URL
1\. User enters email/password
2\. API → sends OTP
3\. Show OTP screen
4\. User enters OTP
5\. API → validate OTP
6\. Success → login
7\. Failure → show error
Folder Structure
src/
│
├── redux/
│ ├── actions/authActions.js
│ ├── reducers/authReducer.js
│ ├── sagas/authSaga.js
│ ├── reducers/rootReducer.js
│ ├── sagas/rootSaga.js
│ └── store.js
│
├── services/authService.js
├── components/Login.js
├── components/OtpVerify.js
├── App.js
└── index.js
1. Actions (Login + OTP)
// authActions.js
export const LOGIN\_REQUEST = "LOGIN\_REQUEST";
export const LOGIN\_SUCCESS = "LOGIN\_SUCCESS";
export const LOGIN\_FAILURE = "LOGIN\_FAILURE";
export const OTP\_REQUEST = "OTP\_REQUEST";
export const OTP\_SUCCESS = "OTP\_SUCCESS";
export const OTP\_FAILURE = "OTP\_FAILURE";
export const loginRequest = (data) => ({
type: LOGIN\_REQUEST,
payload: data,
});
export const otpRequest = (data) => ({
type: OTP\_REQUEST,
payload: data,
});
2. Reducer
// authReducer.js
const initialState = {
loading: false,
user: null,
otpSent: false,
isAuthenticated: false,
error: null,
};
const authReducer = (state = initialState, action) => {
switch (action.type) {
case "LOGIN\_REQUEST":
case "OTP\_REQUEST":
return { ...state, loading: true, error: null };
case "LOGIN\_SUCCESS":
return { ...state, loading: false, otpSent: true };
case "OTP\_SUCCESS":
return {
...state,
loading: false,
isAuthenticated: true,
user: action.payload,
};
case "LOGIN\_FAILURE":
case "OTP\_FAILURE":
return { ...state, loading: false, error: action.payload };
default:
return state;
}
};
export default authReducer;
3. Saga (Core Logic)
// authSaga.js
import { call, put, takeLatest } from "redux-saga/effects";
import {
LOGIN\_REQUEST,
OTP\_REQUEST,
LOGIN\_SUCCESS,
LOGIN\_FAILURE,
OTP\_SUCCESS,
OTP\_FAILURE,
} from "../actions/authActions";
import { loginApi, verifyOtpApi } from "../../services/authService";
// LOGIN SAGA
function\* loginWorker(action) {
try {
const response = yield call(loginApi, action.payload);
// assume API returns success if OTP sent
yield put({ type: LOGIN\_SUCCESS, payload: response.data });
} catch (error) {
yield put({ type: LOGIN\_FAILURE, payload: error.message });
}
}
// OTP VERIFY SAGA
function\* otpWorker(action) {
try {
const response = yield call(verifyOtpApi, action.payload);
yield put({ type: OTP\_SUCCESS, payload: response.data });
} catch (error) {
yield put({ type: OTP\_FAILURE, payload: error.message });
}
}
export default function\* authSaga() {
yield takeLatest(LOGIN\_REQUEST, loginWorker);
yield takeLatest(OTP\_REQUEST, otpWorker);
}
4. Service Layer (Mock REST APIs)
// authService.js
export const loginApi = (data) => {
console.log("Login API called", data);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (data.email === "test\@test.com" && data.password === "1234") {
resolve({ data: { message: "OTP Sent" } });
} else {
reject(new Error("Invalid credentials"));
}
}, 1000);
});
};
export const verifyOtpApi = (data) => {
console.log("Verify OTP API", data);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (data.otp === "123456") {
resolve({ data: { name: "Srikanth", token: "abc123" } });
} else {
reject(new Error("Invalid OTP"));
}
}, 1000);
});
};
5. Login Component
// Login.js
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { loginRequest } from "../redux/actions/authActions";
const Login = () => {
const dispatch = useDispatch();
const { loading, otpSent, error } = useSelector((state) => state.auth);
const [form, setForm] = useState({ email: "", password: "" });
const handleSubmit = (e) => {
e.preventDefault();
dispatch(loginRequest(form));
};
if (otpSent) return null; // hide login
return (
\<div>
\<h2>Login\</h2>
\<form onSubmit={handleSubmit}>
\<input
placeholder="Email"
onChange={(e) => setForm({ ...form, email: e.target.value })}
/>
\<input
placeholder="Password"
type="password"
onChange={(e) => setForm({ ...form, password: e.target.value })}
/>
\<button type="submit">Login\</button>
\</form>
{loading && \<p>Sending OTP...\</p>}
{error && \<p style={{ color: "red" }}>{error}\</p>}
\</div>
);
};
export default Login;
6. OTP Component
// OtpVerify.js
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { otpRequest } from "../redux/actions/authActions";
const OtpVerify = () => {
const dispatch = useDispatch();
const { loading, isAuthenticated, error } = useSelector(
(state) => state.auth
);
const [otp, setOtp] = useState("");
const handleVerify = () => {
dispatch(otpRequest({ otp }));
};
if (isAuthenticated) return \<h2>✅ Login Successful\</h2>;
return (
\<div>
\<h2>Enter OTP\</h2>
\<input onChange={(e) => setOtp(e.target.value)} />
\<button onClick={handleVerify}>Verify OTP\</button>
{loading && \<p>Verifying...\</p>}
{error && \<p style={{ color: "red" }}>{error}\</p>}
\</div>
);
};
export default OtpVerify;
// App.js
import React from "react";
import { useSelector } from "react-redux";
import Login from "./components/Login";
import OtpVerify from "./components/OtpVerify";
function App() {
const { otpSent } = useSelector((state) => state.auth);
return (
\<div>
{!otpSent ? \<Login /> : \<OtpVerify />}
\</div>
);
}
export default App;
Test Credentials
Email: test\@test.com
Password: 1234
OTP: 123456
src/
│
├── app/
│ └── store.js
│
├── features/
│ └── auth/
│ ├── authActions.js
│ ├── authReducer.js
│ ├── authSaga.js
│ ├── authService.js
│ ├── authTypes.js
│
├── routes/
│ └── ProtectedRoute.js
│
├── api/
│ └── axiosClient.js
│
├── pages/
│ ├── Login.js
│ ├── OtpVerify.js
│ └── Dashboard.js
│
├── App.js
└── index.js
export const setTokens = (data) => {
localStorage.setItem("accessToken", data.accessToken);
localStorage.setItem("refreshToken", data.refreshToken);
};
export const getAccessToken = () => {
return localStorage.getItem("accessToken");
};
export const getRefreshToken = () => {
return localStorage.getItem("refreshToken");
};
export const clearTokens = () => {
localStorage.clear();
};
import axios from "axios";
import { getAccessToken, getRefreshToken, setTokens, clearTokens } from "../utils/tokenService";
const api = axios.create({
baseURL: "http\://localhost:8080/api", // your Spring Boot URL
});
// REQUEST INTERCEPTOR
api.interceptors.request.use((config) => {
const token = getAccessToken();
if (token) {
config.headers.Authorization = \`Bearer ${token}\`;
}
return config;
});
// RESPONSE INTERCEPTOR (Refresh Token Logic)
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest.\_retry) {
originalRequest.\_retry = true;
try {
const refreshToken = getRefreshToken();
const res = await axios.post(
"http\://localhost:8080/api/auth/refresh",
{ refreshToken }
);
setTokens(res.data);
originalRequest.headers.Authorization = \`Bearer ${res.data.accessToken}\`;
return api(originalRequest);
} catch (err) {
clearTokens();
window\.location.href = "/login";
}
}
return Promise.reject(error);
}
);
export default api;
**3. Auth Service (Backend Integration)**
import api from "../../api/axiosClient";
export const loginApi = (data) => {
return api.post("/auth/login", data);
};
export const verifyOtpApi = (data) => {
return api.post("/auth/verify-otp", data);
};
export const refreshApi = (data) => {
return api.post("/auth/refresh", data);
};
**4. Update Saga (Store Tokens)**
authSaga.js
import { call, put, takeLatest } from "redux-saga/effects";
import { loginApi, verifyOtpApi } from "./authService";
import { setTokens } from "../../utils/tokenService";
function\* loginWorker(action) {
try {
yield call(loginApi, action.payload);
yield put({ type: "LOGIN\_SUCCESS" });
} catch (e) {
yield put({ type: "LOGIN\_FAILURE", payload: e.message });
}
}
function\* otpWorker(action) {
try {
const res = yield call(verifyOtpApi, action.payload);
// 🔥 SAVE TOKENS HERE
setTokens(res.data);
yield put({ type: "OTP\_SUCCESS", payload: res.data });
} catch (e) {
yield put({ type: "OTP\_FAILURE", payload: e.message });
}
}
export default function\* authSaga() {
yield takeLatest("LOGIN\_REQUEST", loginWorker);
yield takeLatest("OTP\_REQUEST", otpWorker);
}
**5. Protected Route (React Router v6)**
npm install react-router-dom
import React from "react";
import { Navigate } from "react-router-dom";
import { getAccessToken } from "../utils/tokenService";
const ProtectedRoute = ({ children }) => {
const token = getAccessToken();
if (!token) {
return \<Navigate to="/login" />;
}
return children;
};
export default ProtectedRoute;
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Login from "./pages/Login";
import OtpVerify from "./pages/OtpVerify";
import Dashboard from "./pages/Dashboard";
import ProtectedRoute from "./routes/ProtectedRoute";
function App() {
return (
\<BrowserRouter>
\<Routes>
\<Route path="/login" element={\<Login />} />
\<Route path="/otp" element={\<OtpVerify />} />
\<Route
path="/dashboard"
element={
\<ProtectedRoute>
\<Dashboard />
\</ProtectedRoute>
}
/>
\</Routes>
\</BrowserRouter>
);
}
export default App;
const Dashboard = () => {
return \<h1>Welcome to Dashboard 🚀\</h1>;
};
export default Dashboard;
In OTP success:
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
if (isAuthenticated) {
navigate("/dashboard");
}
7. Spring Boot API Contract (IMPORTANT)
Make sure your backend returns:
```
POST /auth/login
{
"email": "test@test.com",
"password": "1234"
}
```
Response:
```
{
"message": "OTP sent"
}
```
```
POST /auth/verify-otp
{
"otp": "123456"
}
```
Response:
```
{
"accessToken": "jwt_token_here",
"refreshToken": "refresh_token_here",
"user": {
"id": 1,
"name": "Srikanth"
}
}
```
```
POST /auth/refresh
{
"refreshToken": "xyz"
}
```
Response:
```
{
"accessToken": "new_token",
"refreshToken": "new_refresh"
}
```
src/
├── api/
│ ├── api.js
│ ├── userService.js
│
├── components/
│ ├── ConfirmDialog.js
│ ├── Loader.js
│
├── pages/
│ ├── Users.js
│ ├── Dashboard.js
│ ├── Login.js
│ ├── Otp.js
│
├── layout/
│ ├── MainLayout.js
│
├── App.js
├── theme.js
1. INSTALL ALL REQUIRED
npm install @mui/material @mui/icons-material @mui/x-data-grid \\
react-toastify\\
Users.js
├── imports
├── function Users()
│ ├── state (confirmOpen, selectedUser)
│ ├── fetchUsers()
│ ├── handleDeleteClick()
│ ├── confirmDelete()
│ ├── columns (DELETE button uses handleDeleteClick)
│ └── return (UI + ConfirmDialog)
Users.js
├── import { toast }
├── useState → loadingId
├── confirmDelete() → toast.success()
App.js
├── ToastContainer (UI)
Frontend (React)
↓
Login → OTP → Token stored
↓
API calls (Axios + Interceptor)
↓
Protected Routes (only with token)
↓
UI Pages (Users / Dashboard / Register)
↓
Actions (Delete / Block / Update)
↓
UX Enhancements (Toast, Loader, Confirm Dialog)
1
React setup + routing
Base app structure
2
Login + OTP
Authentication flow
3
Token storage
Enables secured APIs
4
Axios interceptor
Auto attach token
5
ProtectedRoute
Prevent unauthorized access
6
Users page (DataGrid)
Data display
7
Layout (MainLayout)
Enterprise UI
8
Search + pagination
UX improvement
9
Delete API
Action handling
10
Confirm Dialog
Prevent mistakes
11
Loading state
Prevent duplicate clicks
12
Toast messages
Professional UX
13
Role-based UI
Security control
src/
├── api/
│ ├── api.js
│ ├── userService.js
│
├── components/
│ ├── ConfirmDialog.js
│ ├── ProtectedRoute.js
│ ├── Loader.js
│
├── layout/
│ ├── MainLayout.js
│
├── pages/
│ ├── Login.js
│ ├── Otp.js
│ ├── Users.js
│ ├── Dashboard.js
│ ├── RegisterUser.js
│ ├── ChangePassword.js
│ ├── ResetPassword.js
│
├── App.js
├── theme.js
**INSTALLATION (ONE TIME)**
npm install @mui/material @mui/icons-material @mui/x-data-grid
npm install axios
npm install react-router-dom
npm install react-toastify
1
Login API call
2
OTP verification
3
Store token in localStorage
4
Store username + role
5
Redirect to dashboard
api.js
Base URL + interceptor
userService.js
API methods
Users.js
UI calls API
Attach token
Every request secured
Handle 401
Auto logout
Central error handling
Cleaner code
Page Load
↓
fetchUsers()
↓
API call
↓
Set rows
↓
Render DataGrid
Click DELETE
↓
Open Confirm Dialog
↓
Click Confirm
↓
Set loadingId
↓
Call API
↓
Toast success/error
↓
Refresh table
State
useState
API call
fetchUsers()
Delete logic
confirmDelete()
UI
return JSX
Actions
DataGrid columns
MainLayout
Header + Sidebar
Users
Table + actions
Dashboard
Stats
ConfirmDialog
Reusable popup
Loader
Loading indicator
useState → local state
useEffect → API calls
* ConfirmDialog
* Loader
* API service
* Token-based auth
* Protected routes
* Role-based UI
const role = localStorage.getItem("role");
{role === "ADMIN" && \<DeleteButton />}
Login + OTP
✅
JWT handling
✅
Protected routes
✅
DataGrid
✅
Search
✅
Delete
✅
Confirm dialog
✅
Toast messages
✅
Loading state
✅
Layout
✅
CORS error
Backend config
Token missing
Interceptor
Layout broken
MainLayout fix
DataGrid misaligned
Box width fix
Immediate delete
Confirm dialog
Multiple clicks
loadingId
1\. UI requirement
2\. State needed
3\. API call
4\. UX handling (loading, error)
5\. Security (role/token)
When user clicks **EDIT**
Click EDIT
↓
Popup opens (modal)
↓
Form pre-filled with user data
↓
User updates fields
↓
Click SAVE
↓
API call → update user
↓
Toast + refresh table
STEP 1: Create Edit Dialog Component
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
Grid,
} from "@mui/material";
import { useState, useEffect } from "react";
export default function EditUserDialog({ open, onClose, user, onSave }) {
const [form, setForm] = useState({});
// 🔥 Fill form when dialog opens
useEffect(() => {
if (user) {
setForm(user);
}
}, [user]);
const handleChange = (field, value) => {
setForm({ ...form, [field]: value });
};
return (
\<Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
\<DialogTitle>Edit User\</DialogTitle>
\<DialogContent>
\<Grid container spacing={2} mt={1}>
\<Grid item xs={6}>
\<TextField
label="First Name"
fullWidth
value={form.firstName || ""}
onChange={(e) => handleChange("firstName", e.target.value)}
/>
\</Grid>
\<Grid item xs={6}>
\<TextField
label="Last Name"
fullWidth
value={form.lastName || ""}
onChange={(e) => handleChange("lastName", e.target.value)}
/>
\</Grid>
\<Grid item xs={12}>
\<TextField
label="Email"
fullWidth
value={form.emailId || ""}
onChange={(e) => handleChange("emailId", e.target.value)}
/>
\</Grid>
\<Grid item xs={12}>
\<TextField
label="Phone"
fullWidth
value={form.primaryContactNumber || ""}
onChange={(e) =>
handleChange("primaryContactNumber", e.target.value)
}
/>
\</Grid>
\</Grid>
\</DialogContent>
\<DialogActions>
\<Button onClick={onClose}>Cancel\</Button>
\<Button variant="contained" onClick={() => onSave(form)}>
Save
\</Button>
\</DialogActions>
\</Dialog>
);
}
WHAT THIS DOES
useEffect
loads selected user data
form state
holds editable data
handleChange
updates fields
onSave
sends data back to parent
STEP 2: Add state in Users.js src/pages/Users.js
const [editOpen, setEditOpen] = useState(false);
const [selectedUser, setSelectedUser] = useState(null);
STEP 3: Add EDIT button
{
field: "actions",
headerName: "Actions",
flex: 1.5,
renderCell: (params) => {
const user = params.row;
return (
\<Box sx={{ display: "flex", gap: 1 }}>
\<Button
size="small"
variant="contained"
color="primary"
onClick={() => {
setSelectedUser(user);
setEditOpen(true);
}}
>
EDIT
\</Button>
{/\* existing DELETE button \*/}
\</Box>
);
},
}
STEP 4: Add UPDATE API call
Inside Users.js
const handleUpdateUser = async (updatedUser) => {
try {
await api.put(\`/api/user/${updatedUser.credentialId}\`, updatedUser);
toast.success("User updated successfully");
setEditOpen(false);
fetchUsers(); // refresh table
} catch {
toast.error("Update failed");
}
};
STEP 5: Add Dialog in JSX
At bottom of Users.js (inside return)
import EditUserDialog from "../components/EditUserDialog";
\<EditUserDialog
open={editOpen}
onClose={() => setEditOpen(false)}
user={selectedUser}
onSave={handleUpdateUser}
/>
FINAL FLOW
Click EDIT
↓
Dialog opens
↓
Form auto-filled
↓
User updates data
↓
Click SAVE
↓
API call
↓
Toast success
↓
Table refresh
Click EDIT
↓
Dialog opens
↓
User edits fields
↓
Click Save
↓
Validation runs
↓
If error → show message
↓
If valid → API call
↓
Button shows "Saving..."
↓
Toast success
↓
Table refresh
import Collapse from "@mui/material/Collapse";
import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
const [userOpen, setUserOpen] = useState(false);
const [donorOpen, setDonorOpen] = useState(false);
\<List>
{/\* DASHBOARD \*/}
\<ListItemButton onClick={() => navigate("/dashboard")}>
\<ListItemIcon>\<DashboardIcon />\</ListItemIcon>
{open && \<ListItemText primary="Dashboard" />}
\</ListItemButton>
{/\* ================= USERS ================= \*/}
\<ListItemButton onClick={() => setUserOpen(!userOpen)}>
\<ListItemIcon>\<PeopleIcon />\</ListItemIcon>
{open && \<ListItemText primary="Users" />}
{userOpen ? \<ExpandLess /> : \<ExpandMore />}
\</ListItemButton>
\<Collapse in={userOpen} timeout="auto" unmountOnExit>
\<List component="div" disablePadding>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/register")}>
\<ListItemText primary="Register User" />
\</ListItemButton>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/change-password")}>
\<ListItemText primary="Change Password" />
\</ListItemButton>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/users")}>
\<ListItemText primary="Edit User" />
\</ListItemButton>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/users")}>
\<ListItemText primary="Remove User" />
\</ListItemButton>
\</List>
\</Collapse>
{/\* ================= DONORS ================= \*/}
\<ListItemButton onClick={() => setDonorOpen(!donorOpen)}>
\<ListItemIcon>💰\</ListItemIcon>
{open && \<ListItemText primary="Donors" />}
{donorOpen ? \<ExpandLess /> : \<ExpandMore />}
\</ListItemButton>
\<Collapse in={donorOpen} timeout="auto" unmountOnExit>
\<List component="div" disablePadding>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/donors")}>
\<ListItemText primary="Add Donor" />
\</ListItemButton>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/donors")}>
\<ListItemText primary="Edit Donor" />
\</ListItemButton>
\<ListItemButton sx={{ pl: 4 }} onClick={() => navigate("/donors")}>
\<ListItemText primary="View Donor" />
\</ListItemButton>
\</List>
\</Collapse>
{/\* ================= OTHER MODULES ================= \*/}
\<ListItemButton onClick={() => navigate("/donor-payments")}>
{open && \<ListItemText primary="Donor Payments" />}
\</ListItemButton>
\<ListItemButton onClick={() => navigate("/committee")}>
{open && \<ListItemText primary="Committee" />}
\</ListItemButton>
\<ListItemButton onClick={() => navigate("/volunteers")}>
{open && \<ListItemText primary="Volunteers" />}
\</ListItemButton>
\<ListItemButton onClick={() => navigate("/reports")}>
{open && \<ListItemText primary="Reports" />}
\</ListItemButton>
\</List>
| Phase | What You Did | Why It Matters |
|---|---|---|
| 1 | React setup + routing | Base application structure |
| 2 | Login + OTP | Authentication flow |
| 3 | Token storage | Enables secured APIs |
| 4 | Axios interceptor | Automatically attaches tokens |
| 5 | ProtectedRoute | Prevents unauthorized access |
| 6 | Users page / DataGrid | Structured data display |
| 7 | MainLayout | Enterprise UI structure |
| 8 | Search + pagination | Better usability |
| 9 | Delete API | Action handling |
| 10 | Confirm Dialog | Prevents accidental actions |
| 11 | Loading state | Prevents duplicate clicks |
| 12 | Toast messages | Professional UX feedback |
| 13 | Role-based UI | Additional security control |