React Js / APIs / login and token storing
Manage token
-
1. Step
Token Management Flow
1. Login and Get token
2. Store token (in memory, localStorage, or sessionStorage)
3. Send token in API headers
React: Login Form and Store Token
src/components/Login.jsx
); }; export default Login;import { useState } from 'react'; const Login = ({ onLogin }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch('https://your-api.com/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); if (res.ok) { const data = await res.json(); const token = data.token; localStorage.setItem('token', token); // Save token onLogin(token); // Pass token to parent/app } else { alert('Login failed'); } }; return ( 3. Authenticated API Call Using Token
src/components/UserList.jsx
import { useEffect, useState } from 'react'; const UserList = () => { const [users, setUsers] = useState([]); const token = localStorage.getItem('token'); useEffect(() => { fetch('https://your-api.com/api/users', { headers: { 'Authorization': `Bearer ${token}` } }) .then(res => { if (!res.ok) throw new Error('Unauthorized or failed'); return res.json(); }) .then(data => setUsers(data)) .catch(err => console.error(err.message)); }, []); return ( -
{users.map(u => (
- {u.name} ))}
MANVIA BLOG