Authentication & Authorization
Implementing Authentication for Each Page/Route
1. AuthProvider
const { isAuthenticated, loading, login, logout } = useAuth();Usage Example:
import React, { createContext, useContext, useState, ReactNode, FC } from 'react';
interface AuthContextType {
isAuthenticated: boolean;
loading: boolean;
login: () => void;
logout: () => void;
authUser?: any; // Add this if you want to provide user information
}
const AuthContext = createContext<AuthContextType | null>(null);
export const AuthProvider: FC<{ children: ReactNode }> = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [authUser, setAuthUser] = useState<any>(null); // Manage user information
const login = () => {
setLoading(true);
// Add your login logic here
setIsAuthenticated(true);
setAuthUser({ name: 'John Doe' }); // Example user info
setLoading(false);
};
const logout = () => {
// Add your logout logic here
setIsAuthenticated(false);
setAuthUser(null);
};
return (
<AuthContext.Provider value={{ isAuthenticated, loading, login, logout, authUser }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};2. Creating a HOC Function
3. Page Component
Usage Example:
Defining Routes:
Last updated