Frontend Utilities
Overview
The frontend utilities provide essential helper functions and configurations that support the React application. These utilities handle API communication, data validation, and common operations used throughout the application.
What are Utility Functions?
Utility functions are reusable pieces of code that perform common tasks across an application. They help:
- Avoid code duplication by centralizing common logic
- Maintain consistency in how operations are performed
- Simplify testing by isolating functionality
- Improve maintainability by keeping code organized
API Communication Utility
File: frontend/notes-app/src/utils/axiosInstance.js
This utility configures HTTP communication with the backend API using Axios, a popular JavaScript library for making HTTP requests.
import axios from "axios";
import { BASE_URL } from "./constant";
const axiosInstance = axios.create({
baseURL: BASE_URL,
timeout: 10000,
headers: {
"Content-Type": "application/json"
}
});
Configuration Explained
axios.create()
: Creates a customized Axios instance with predefined settingsbaseURL
: Sets the default server URL for all requeststimeout: 10000
: Automatically cancels requests after 10 secondsheaders
: Sets default headers for all requests
Automatic Authentication
The utility includes an interceptor that automatically adds authentication tokens to requests:
axiosInstance.interceptors.request.use(
(config) => {
const accessToken = localStorage.getItem("token");
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
How Interceptors Work
Interceptors are functions that run automatically before requests are sent or after responses are received. This request interceptor:
- Runs before every HTTP request is sent to the server
- Retrieves the JWT token from browser's localStorage
- Adds Authorization header if a token exists
- Returns the modified config to continue the request
- Handles errors by rejecting the promise
Key Concepts
localStorage.getItem("token")
: Retrieves stored authentication token from browser storageconfig.headers.Authorization
: Sets the HTTP Authorization headerBearer ${accessToken}
: Standard format for JWT token authenticationPromise.reject(error)
: Passes errors to the calling code
Benefits of This Approach
- Automatic authentication: No need to manually add tokens to each request
- Centralized configuration: All API settings in one place
- Consistent error handling: Standardized approach across the application
- Easy maintenance: Changes to API configuration affect the entire app
Configuration Constants
File: frontend/notes-app/src/utils/constant.js
export const BASE_URL = "http://localhost:8000"
This file defines application-wide constants:
BASE_URL
: The backend server address- Centralized configuration: Easy to change for different environments (development, production)
- Import/export syntax: Uses ES6 modules for sharing values between files
Helper Functions
File: frontend/notes-app/src/utils/helper.js
Contains utility functions for common operations used throughout the application.
Email Validation
export const validateEmail = (email) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
};
Function Breakdown
- Purpose: Validates if a string is a properly formatted email address
- Parameter:
email
- the string to validate - Returns:
true
if valid email format,false
otherwise - Regex pattern:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
matches standard email format
Regex Pattern Explained
^
: Start of string[^\s@]+
: One or more characters that are not whitespace or @ symbol@
: Literal @ symbol[^\s@]+
: One or more characters that are not whitespace or @ symbol\.
: Literal dot (escaped because . has special meaning in regex)[^\s@]+
: One or more characters that are not whitespace or @ symbol$
: End of string
Name Initials Generator
export const getInitials = (name) => {
if(!name) return "";
const words = name.split(" ");
let initials = "";
for(let i=0; i < Math.min(words.length,2); i++){
initials += words[i][0];
}
return initials.toUpperCase();
};
Function Breakdown
- Purpose: Extracts initials from a person's name for display (e.g., "John Doe" → "JD")
- Parameter:
name
- the full name string - Returns: Uppercase initials string (maximum 2 characters)
Logic Flow
- Guard clause: Returns empty string if no name provided
- Split name:
name.split(" ")
creates array of words - Loop through words: Takes first character of each word
- Limit to 2 initials:
Math.min(words.length,2)
prevents more than 2 letters - Convert to uppercase:
toUpperCase()
for consistent display
Usage Examples
getInitials("John Doe") // Returns "JD"
getInitials("Alice") // Returns "A"
getInitials("Mary Jane Watson") // Returns "MJ" (only first 2 words)
getInitials("") // Returns ""
Application Entry Point
File: frontend/notes-app/src/main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
Entry Point Explained
ReactDOM.createRoot()
: Creates a React 18 root for renderingdocument.getElementById('root')
: Finds the HTML element where React will mountReact.StrictMode
: Development mode wrapper that helps identify problems<App />
: The main application component
Application Routing
File: frontend/notes-app/src/App.jsx
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from './pages/Home/Home'
import Login from "./pages/Login/Login"
import SignUp from "./pages/SignUp/SignUp"
import Modal from "react-modal";
Modal.setAppElement('#root');
const routes = (
<Router>
<Routes>
<Route path="/dashboard" exact element={<Home />}/>
<Route path="/login" exact element={<Login />}/>
<Route path="/signup" exact element={<SignUp />}/>
</Routes>
</Router>
);
Routing Concepts
BrowserRouter
: Enables client-side routing using browser historyRoutes
: Container for all route definitionsRoute
: Maps URL paths to React componentsModal.setAppElement('#root')
: Configures modal accessibility
Route Definitions
/dashboard
: Main application interface (Home component)/login
: User authentication page/signup
: User registration page
Connection to Other Components
Backend Integration
- axiosInstance: Communicates with backend API endpoints
- Authentication: Automatically includes JWT tokens in requests
- Error handling: Manages API communication failures
Component Usage
- Email validation: Used in login and signup forms
- Initials generation: Used in user profile displays
- Routing: Connects different pages and user flows
State Management
- localStorage: Stores authentication tokens persistently
- Browser history: Manages navigation between pages
- Component props: Utilities passed down to child components