Nodejs-Assignment-9
Implement User registration & Login operations in the app.
Here , Iam sharing some sample code for your ref.
loginContext.js
--------------------
import {createContext} from 'react';
export const loginContext=createContext({})
UserLoginStore.js
-----------------------
import React, { useState } from "react";
import { loginContext } from "./loginContext";
import axios from "axios";
function UserLoginStore({ children }) {
const [currentUser, setCurrentUser] = useState({});
const [loginErr, setLoginErr] = useState("");
const [userLoginStatus,setUserLoginStatus]=useState(false)
//login user
const loginUser = (userCredObj) => {
axios
.post("http://localhost:3500/user-api/login", userCredObj)
.then((response) => {
if (response.data.message === "success") {
console.log(response)
//save token to local storage
localStorage.setItem("token",response.data.token)
setCurrentUser({...response.data.user});
setLoginErr("");
setUserLoginStatus(true)
} else {
setLoginErr(response.data.message);
}
})
.catch((err) => {
console.log("err",err)
setLoginErr(err.message);
});
};
//logout user
const logoutUser=()=>{
localStorage.clear()
setUserLoginStatus(false)
}
return (
<loginContext.Provider value={[currentUser,loginErr,userLoginStatus,loginUser,logoutUser]}>
{children}
</loginContext.Provider>
);
}
export default UserLoginStore;
Login.js
----------
import { useState,useContext ,useEffect} from "react";
import "./Login.css";
import { useForm } from "react-hook-form";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { loginContext } from "../../contexts/loginContext";
function Login() {
let [currentUser,loginErr,userLoginStatus,loginUser]=useContext(loginContext)
//error state
let [error, setError] = useState("");
//navigate
const navigate = useNavigate();
//use form hook
let {
register,
handleSubmit,
formState: { errors },
} = useForm();
//adding new user
let handleSubmitUser = (userCredObj) => {
loginUser(userCredObj)
};
useEffect(()=>{
if(userLoginStatus===true){
navigate("/user-profile")
}
},[userLoginStatus])
return (
<div className="add-user">
{/* form submission error */}
{loginErr.length !== 0 && (
<p className="display-3 text-danger text-center">{loginErr}</p>
)}
{/* add user form */}
<div className="row">
<div className="col-11 col-sm-8 col-md-6 mx-auto">
<form onSubmit={handleSubmit(handleSubmitUser)}>
{/* username */}
<div className="mb-3">
<label htmlFor="name">Userame</label>
<input
type="text"
id="username"
className="form-control"
{...register("username", { required: true })}
/>
{/* validation errors for name */}
{errors.username?.type === "required" && (
<p className="text-danger fw-bold fs-5">
* Username is required
</p>
)}
</div>
{/* password */}
<div className="mb-3">
<label htmlFor="name">Password</label>
<input
type="password"
id="password"
className="form-control"
{...register("password", { required: true })}
/>
{/* validation errors for name */}
{errors.password?.type === "required" && (
<p className="text-danger fw-bold fs-5">
* Password is required
</p>
)}
</div>
{/* submit button */}
<button type="submit" className="btn add-user-btn">
Login
</button>
</form>
</div>
</div>
</div>
);
}
export default Login;
App.js
--------
import './App.css';
import Home from './components/home/Home';
import Register from './components/register/Register';
import Login from './components/login/Login';
import Aboutus from './components/aboutus/Aboutus';
import UserProfile from './components/user-profile/UserProfile';
import Products from './components/products/Products';
import Cart from './components/cart/Cart'
import ErrorPage from './components/ErrorPage';
import { createBrowserRouter , RouterProvider } from 'react-router-dom';
import RootLayout from './RootLayout';
import { loginContext } from './contexts/loginContext';
import {useContext} from 'react'
function App() {
//create BrowserRouter object
const browserRouter=createBrowserRouter([
{
path:"/",
element:<RootLayout />,
errorElement:<ErrorPage />,
children:[
//route for add user
{
path:"/",
element:<Home />
},
//route for Users
{
path:"/register",
element:<Register />
},
//route for removed users
{
path:"/login",
element:<Login />
},
//route for removed users
{
path:"/aboutus",
element:<Aboutus />
},
//route for user-profile
{
path:"/user-profile",
element:<UserProfile />,
children:[
{
path:"products",
element:<Products />
},
{
path:"cart",
element:<Cart />
}
]
}
]
}
])
return (
<div>
<RouterProvider router={browserRouter} />
</div>
);
}
export default App;
Index.js
---------
import "bootstrap/dist/css/bootstrap.min.css";
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import UserLoginStore from "./contexts/UserLoginStore";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<UserLoginStore>
<App />
</UserLoginStore>
);
UserProfile.js
----------------
import React,{useContext} from 'react';
import { loginContext } from '../../contexts/loginContext';
import './UserProfile.css';
import {NavLink,Outlet} from 'react-router-dom'
function UserProfile() {
let [currentUser]=useContext(loginContext)
const activeLink = {
color: "#ffaa00",
fontSize: "1.2rem",
fontWeight: "bold",
};
const inactiveLink = {
color: "black",
fontSize: "1.2rem",
};
return (
<div>
<p className="display-5 text-end">Welcome ,{currentUser.username}</p>
<p className="display-6 text-end"> <small>{currentUser.email}</small></p>
<img src={currentUser.image} width="50px" alt="" className='float-end' />
<ul className="nav justify-content-between">
<li className="nav-item">
<NavLink
className="nav-link"
to="products"
style={({ isActive }) => {
return isActive ? activeLink : inactiveLink;
}}
>
Products
</NavLink>
</li>
<li className="nav-item">
<NavLink
className="nav-link"
to="cart"
style={({ isActive }) => {
return isActive ? activeLink : inactiveLink;
}}
>
Cart
</NavLink>
</li>
</ul>
<Outlet />
</div>
)
}
export default UserProfile
Comments
Post a Comment