API Authentication Using Laravel Sanctum and React js Part 3
In the third part of this tutorial, we will register and log in the user, get the access token, and use it to log out the user.
Display laravel validation errors
Always inside helpers let's create a new file 'validation.js' that contains the code to display the validation errors.
export const renderValidationErrors = (errors, field) => {
return errors?.[field]?.length && errors[field].map((error, index) => {
return <div key={ index } className="alert alert-danger" role="alert">
{ error }
</div>
})
};
Update App.js
Next, let's update the App component create the routes, and fetch the currently logged-in user.
import { useEffect, useState } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import Header from './components/layouts/Header';
import { AuthContext } from './helpers/authContext';
import axios from 'axios';
import { BASE_URL } from './helpers/url';
import { getConfig } from './helpers/config';
function App() {
const [accessToken, setAccessToken] = useState(JSON.parse(localStorage.getItem("accessToken")));
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
const fetchCurrentUser = async () => {
try {
const response = await axios.get(`${BASE_URL}/user`, getConfig(accessToken));
setCurrentUser(response.data.user);
} catch (error) {
if (error.response.status === 401) {
localStorage.removeItem('accessToken');
setCurrentUser(null);
setAccessToken('');
}
console.log(error);
}
}
fetchCurrentUser();
}, []);
return (
<AuthContext.Provider value={{accessToken, setAccessToken, currentUser, setCurrentUser}}>
<BrowserRouter>
<Header />
<Routes>
<Route path="/register" element={<Register />} />
<Route path="/Login" element={<Login />} />
</Routes>
</BrowserRouter>
</AuthContext.Provider>
);
}
export default App;
Header component
Next, inside src create a new folder 'components' inside create a new folder 'layouts' inside add a new file 'Header.jsx'.
> components
>> layouts
>>> Header.jsx
import React, { useContext } from 'react'
import { Link, useLocation } from 'react-router-dom';
import { AuthContext } from '../../helpers/authContext';
import axios from 'axios';
import { BASE_URL } from '../../helpers/url';
import { getConfig } from '../../helpers/config';
import { toast } from 'react-toastify';
export default function Header() {
const { accessToken, setAccessToken, currentUser, setCurrentUser } = useContext(AuthContext);
const location = useLocation();
const logout = async () => {
try {
await axios.post(`${BASE_URL}/user/logout`, {} , getConfig(accessToken));
localStorage.removeItem('accessToken');
setCurrentUser(null);
setAccessToken('');
toast.success('Logged out successfully', {
position: toast.POSITION.TOP_RIGHT
});
} catch (error) {
console.log(error);
}
}
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid">
<button
className="navbar-toggler"
type="button"
data-mdb-toggle="collapse"
data-mdb-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<i className="fas fa-bars"></i>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<Link to="/" className="navbar-brand mt-2 mt-lg-0">
Laravel & React Auth App
</Link>
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link to="/" className={`nav-link ${location.pathname === '/' ? 'active' : ''}`}>
<i className="fas fa-home"></i> Home
</Link>
</li>
{
!currentUser ? <>
<li className="nav-item">
<Link to="/register" className={`nav-link ${location.pathname === '/register' ? 'active' : ''}`}>
<i className="fas fa-user-plus"></i> Register
</Link>
</li>
<li className="nav-item">
<Link to="/login" className={`nav-link ${location.pathname === '/login' ? 'active' : ''}`}>
<i className="fas fa-sign-in"></i> Login
</Link>
</li>
</> :
<>
<li className="nav-item">
<Link to="#" className={`nav-link ${location.pathname === '#' ? 'active' : ''}`}>
<i className="fas fa-user"></i> { currentUser.name }
</Link>
</li>
<li className="nav-item">
<Link to="#" onClick={() => logout()} className="nav-link">
<i className="fas fa-sign-out"></i> Logout
</Link>
</li>
</>
}
</ul>
</div>
</div>
</nav>
)
}
Register component
Next, inside components create a new folder 'auth' inside add a new file 'Register.jsx'.
> components
>> layouts
>>> Header.jsx
>> auth
>>> Register.jsx
import axios from 'axios';
import React, { useContext, useEffect, useState } from 'react';
import { BASE_URL } from '../../helpers/url';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../../helpers/authContext';
import { renderValidationErrors } from '../../helpers/validation';
import { toast } from 'react-toastify';
export default function Register() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState({});
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const { accessToken, setAccessToken, setCurrentUser } = useContext(AuthContext);
useEffect(() => {
if(accessToken) {
navigate('/');
}
}, [accessToken]);
const handleSubmit = async (e) => {
e.preventDefault();
setErrors({});
setLoading(true);
const data = { name, email, password };
try {
const response = await axios.post(`${BASE_URL}/user/register`, data);
localStorage.setItem('accessToken', JSON.stringify(response.data.access_token));
setCurrentUser(response.data.user);
setAccessToken(response.data.access_token);
setLoading(false);
setName('');
setEmail('');
setPassword('');
toast.success('Account created successfully', {
position: toast.POSITION.TOP_RIGHT
});
navigate('/');
} catch (error) {
setLoading(false);
if (error.response.status === 422) {
setErrors(error.response.data.errors);
}
console.log(error);
}
}
return (
<div className="container">
<div className="row my-5">
<div className="col-md-6 mx-auto">
<div className="card">
<div className="card-header bg-white p-3 text-center">
<h4>Register</h4>
</div>
<div className="card-body">
<form onSubmit={ (e) => handleSubmit(e) } noValidate>
<div className="row mb-4">
<div className="col">
<div className="form-group">
<input type="text"
name="name"
value={name}
onChange={ event => setName(event.target.value) }
className="form-control mb-2 rounded-0" placeholder="Name"/>
{ renderValidationErrors(errors, 'name') }
</div>
</div>
</div>
<div className="form-group mb-4">
<input type="email" name="email"
value={email}
onChange={ event => setEmail(event.target.value) }
className="form-control mb-2 rounded-0" placeholder="Email" />
{ renderValidationErrors(errors, 'email') }
</div>
<div className="form-group mb-4">
<input type="password"
name="password"
value={password}
onChange={ event => setPassword(event.target.value) }
className="form-control mb-2 rounded-0" placeholder="Password"/>
{ renderValidationErrors(errors, 'password') }
</div>
{
loading ? <div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
:
<button type="submit" className="btn btn-primary btn-block mb-4 rounded-0">Sign up</button>
}
</form>
</div>
</div>
</div>
</div>
</div>
)
}
Login component
Next, inside auth add a new file 'Login.jsx'.
> components
>> layouts
>>> Header.jsx
>> auth
>>> Register.jsx
>>> Login.jsx
NB: for styling & icons I have already added Bootstrap and font-awesome icons inside the index.html file.
font-awesome CDN:
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css
Bootstrap CDN:
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js
import axios from 'axios';
import React, { useContext, useEffect, useState } from 'react';
import { BASE_URL } from '../../helpers/url';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../../helpers/authContext';
import { renderValidationErrors } from '../../helpers/validation';
export default function Login() {
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [errors, setErrors] = useState({});
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const { accessToken, setAccessToken, setCurrentUser } = useContext(AuthContext);
useEffect(() => {
if(accessToken) {
navigate('/');
}
}, [accessToken]);
const handleSubmit = async (e) => {
e.preventDefault();
setErrors({});
setLoading(true);
const data = { email, password };
try {
const response = await axios.post(`${BASE_URL}/user/login`, data);
localStorage.setItem('accessToken', JSON.stringify(response.data.access_token));
setCurrentUser(response.data.user);
setAccessToken(response.data.access_token);
setLoading(false);
setEmail('');
setPassword('');
navigate('/');
} catch (error) {
setLoading(false);
if (error.response.status === 422) {
setErrors(error.response.data.errors);
}
console.log(error);
}
}
return (
<div className="container">
<div className="row my-5">
<div className="col-md-6 mx-auto">
<div className="card">
<div className="card-header bg-white p-3 text-center">
<h4>Login</h4>
</div>
<div className="card-body">
<form onSubmit={ (e) => handleSubmit(e) } noValidate>
<div className="form-group mb-4">
<input type="email" name="email"
value={email}
onChange={ event => setEmail(event.target.value) }
className="form-control mb-2 rounded-0" placeholder="Email" />
{ renderValidationErrors(errors, 'email') }
</div>
<div className="row mb-4">
<div className="col">
<div className="form-group">
<input type="password"
name="password"
value={password}
onChange={ event => setPassword(event.target.value) }
className="form-control mb-2 rounded-0" placeholder="Password"/>
{ renderValidationErrors(errors, 'password') }
</div>
</div>
</div>
{
loading ? <div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
:
<button type="submit" className="btn btn-primary btn-block mb-4 rounded-0">Sign in</button>
}
</form>
</div>
</div>
</div>
</div>
</div>
)
}