Java + ReactJS Full Stack Notes

Cleaned and structured ReactJS, Redux, authentication, JWT, Axios, Material UI and enterprise UI notes.

Source content preserved and organized

Important Concepts at a Glance

ConceptPurpose
PropsPass data from parent to child components.
StateMaintain component-local, changing data.
HooksUse state and other React features in functional components.
ReduxManage predictable application state.
Redux-SagaHandle asynchronous side effects such as API calls.
Axios InterceptorAttach access tokens and centralize 401/refresh handling.
ProtectedRouteRestrict routes when an access token is absent.
DataGridDisplay and manage tabular user data.
ConfirmDialogRequire confirmation before destructive actions.
ToastProvide success/error feedback to the user.
Role-based UIShow or hide UI actions according to the user's role.

Java ReactJs flow

A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES

1.     ReactJS

ü  **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

2.     PROPS

ü  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

3.     STATE

ü  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.

4.     UNIDIRECTIONAL (ONE WAY) DATA FLOW

ü  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

5.     COMPONENT TYPES

6.     FUNCTIONAL COMPONENTS

7.     CLASS BASED COMPONENT

8.     COMPONENT LIFE CYCLE METHODS

9.     WORKING WITH FORMS

10.  HOOKS

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

11.  REDUX : OVERVIEW

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.

12.  Actions

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()

13.  REDUCER

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.

14.  Store

15.  DATA FLOW IN REDUX

16.  Memoization

**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:

1. React.memo()

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.

1.     useMemo()

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.

17.  convert Array into flat array like

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));

18.  Key highlights of React 18 (and recent updates):

ü  **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

19.  Step-by-Step Setup on Windows 11

1. Install Required Tools

👉 Verify installation:

node -v

npm -v

2. Create React App

Open **Command Prompt / PowerShell / VS Code Terminal**:

npx create-react-app react-saga-auth

cd react-saga-auth

3. Install Dependencies

npm install redux react-redux redux-saga axios

Open Project in VS Code (Recommended)

code .

If code command doesn’t work:

5. Create Folder Structure

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

1        Issue 2: Port Already in Use

If port 3000 is busy:

npm start

It will ask:

Would you like to run on another port? (Y/N)

👉 Press **Y**

2        Issue 3: Node Modules Error

Fix by reinstalling:

rm -rf node\_modules

npm install

(On Windows, if rm fails:)

rd /s /q node\_modules

npm install

▶️ 6. Run Application

npm start

👉 App opens at:

http\://localhost:3000

🧪 Test Login

Use this:

email: eve\@reqres.in

password: cityslicka

3        Use Git Bash (Better than CMD)

Install:

👉 [https://git-scm.com/](https://git-scm.com/)

Then right-click → **Git Bash Here**

4        ✔ Use .env file for API URL

Create .env in root:

REACT\_APP\_API\_URL=https\://reqres.in/api

Update service:

baseURL: process.env.REACT\_APP\_API\_URL

5        Flow Overview

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;

7. App Integration

// 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

Enterprise Folder Structure

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

JWT Storage Utilities

👉 utils/tokenService.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();

};

Axios Interceptor (CRITICAL)

👉 api/axiosClient.js

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)**

features/auth/authService.js

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

6.     routes/ProtectedRoute.js

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;

Routing Setup

👉 App.js

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;

Dashboard Page

const Dashboard = () => {

  return \<h1>Welcome to Dashboard 🚀\</h1>;

};

export default Dashboard;

Redirect After Login

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:

Login API

```

POST /auth/login



{

"email": "test@test.com",

"password": "1234"

}

```

Response:

```

{

"message": "OTP sent"

}

```

Verify OTP

```

POST /auth/verify-otp



{

"otp": "123456"

}

```

Response:

```

{

"accessToken": "jwt_token_here",

"refreshToken": "refresh_token_here",

"user": {

"id": 1,

"name": "Srikanth"

}

}

```

Refresh Token

```

POST /auth/refresh



{

"refreshToken": "xyz"

}

```

Response:

```

{

"accessToken": "new_token",

"refreshToken": "new_refresh"

}

```

Project Structure

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)

COMPLETE SUMMARY (END-TO-END FLOW)

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)

PHASE-WISE SUMMARY

Phase

What You Did

Why It Matters

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

COMPLETE FILE STRUCTURE

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

AUTHENTICATION FLOW

Step

Action

1

Login API call

2

OTP verification

3

Store token in localStorage

4

Store username + role

5

Redirect to dashboard

API FLOW

Layer

Responsibility

api.js

Base URL + interceptor

userService.js

API methods

Users.js

UI calls API

INTERCEPTOR ROLE

Feature

Purpose

Attach token

Every request secured

Handle 401

Auto logout

Central error handling

Cleaner code

USERS PAGE FLOW

Page Load

↓

fetchUsers()

↓

API call

↓

Set rows

↓

Render DataGrid

DELETE FLOW (PRODUCTION)

Click DELETE

↓

Open Confirm Dialog

↓

Click Confirm

↓

Set loadingId

↓

Call API

↓

Toast success/error

↓

Refresh table

USERS.JS RESPONSIBILITIES

Feature

Code Location

State

useState

API call

fetchUsers()

Delete logic

confirmDelete()

UI

return JSX

Actions

DataGrid columns

UI ARCHITECTURE

Component

Purpose

MainLayout

Header + Sidebar

Users

Table + actions

Dashboard

Stats

ConfirmDialog

Reusable popup

Loader

Loading indicator

IMPORTANT CONCEPTS

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 />}

PRODUCTION FEATURES

Feature

Status

Login + OTP

✅

JWT handling

✅

Protected routes

✅

DataGrid

✅

Search

✅

Delete

✅

Confirm dialog

✅

Toast messages

✅

Loading state

✅

Layout

✅

COMMON MISTAKES

Mistake

Fix

CORS error

Backend config

Token missing

Interceptor

Layout broken

MainLayout fix

DataGrid misaligned

Box width fix

Immediate delete

Confirm dialog

Multiple clicks

loadingId

HOW TO BUILD YOUR OWN FEATURE

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

Part

Purpose

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

Add state

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

In MainLayout.js

STEP 1: IMPORT REQUIRED COMPONENTS

import Collapse from "@mui/material/Collapse";

import ExpandLess from "@mui/icons-material/ExpandLess";

import ExpandMore from "@mui/icons-material/ExpandMore";

STEP 2: ADD STATE

const [userOpen, setUserOpen] = useState(false);

const [donorOpen, setDonorOpen] = useState(false);

STEP 3: UPDATE SIDEBAR

\<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-Wise Project Summary

PhaseWhat You DidWhy It Matters
1React setup + routingBase application structure
2Login + OTPAuthentication flow
3Token storageEnables secured APIs
4Axios interceptorAutomatically attaches tokens
5ProtectedRoutePrevents unauthorized access
6Users page / DataGridStructured data display
7MainLayoutEnterprise UI structure
8Search + paginationBetter usability
9Delete APIAction handling
10Confirm DialogPrevents accidental actions
11Loading statePrevents duplicate clicks
12Toast messagesProfessional UX feedback
13Role-based UIAdditional security control