Skip to content

Instantly share code, notes, and snippets.

@Bhavya8181
Last active February 12, 2024 05:41
Show Gist options
  • Save Bhavya8181/c9caca33b4c6e27c417ff32381001dc9 to your computer and use it in GitHub Desktop.
Save Bhavya8181/c9caca33b4c6e27c417ff32381001dc9 to your computer and use it in GitHub Desktop.
React Learning
In react js you can store&use enviorment variable
- Create .env file in root of project
- Add variable with "REACT_APP" prefix (REACT_APP prefix must be required in every variable name)
- Use env variable using "process.env.varaible_name"
For Ex:
1. add variable in .env file
REACT_APP_API_ENDPOINT="http://20.169.229.247/saasoa_back/api"
2. Use variable in any page
const BASE_URL = process.env.REACT_APP_API_ENDPOINT;
Login Functionality
=====================
Ref Link:- https://dev.to/sanjayttg/jwt-authentication-in-react-with-react-router-1d03
Steps to impliment Login functionality in your page
1. create authProvider.js file inside src/provider and paste blow code into authProvide.js File
import axios from "axios";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
const AuthContext = createContext();
const AuthProvider = ({ children }) => {
// State to hold the authentication token
const [token, setToken_] = useState(localStorage.getItem("token"));
// Function to set the authentication token
const setToken = (newToken) => {
setToken_(newToken);
};
useEffect(() => {
if (token) {
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
localStorage.setItem('token',token);
} else {
delete axios.defaults.headers.common["Authorization"];
localStorage.removeItem('token')
}
}, [token]);
// Memoized value of the authentication context
const contextValue = useMemo(
() => ({
token,
setToken,
}),
[token]
);
// Provide the authentication context to the children components
return (
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
};
export const useAuth = () => {
return useContext(AuthContext);
};
export default AuthProvider;
2. creating a ProtectedRoute.jsx Component for Authenticated Routes and Copy & Paste below code
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "provider/authProvider";
export const ProtectedRoute = ({children}) => {
const { token } = useAuth();
// Check if the user is authenticated
if (!token) {
// If not authenticated, redirect to the login page
return <Navigate to="/auth/login" />;
}
return children;
// If authenticated, render the child routes
// return <Outlet />;
};
3. Authenticated users routes wraped with yout ProtectedRoute component
For Ex: <Route path="/admin/index" element={<ProtectedRoute> <Component /> </ProtectedRoute>} />
4. The AuthProvider component is used to provide the authentication context to the application. It wraps around the Routes component
to make the authentication context available to all components within the Routes component tree.
For Ex: return (
<AuthProvider>
<Routes />
</AuthProvider>
);
5. Now implement Login and Logout
const handleLogin = () => {
//Login to call api for login and get token
//store token using setToken function
setToken(token);
navigate("/", { replace: true });
};
const handleLogout = () => {
setToken();
navigate("/", { replace: true });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment