Last active
July 4, 2024 03:01
-
-
Save sineto/52d6a4f634cb51c2a6e6013dc64be47b to your computer and use it in GitHub Desktop.
User Authentication with Context API and Hooks (useContext, useState)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { BrowserRouter } from 'react-router-dom'; | |
import { UserProvider } from './services/UserContext'; | |
import Routes from './Routes' | |
function App() { | |
return ( | |
<BrowserRouter> | |
<UserProvider> | |
<Routes /> | |
</UserProvider> | |
</BrowserRouter> | |
); | |
} | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import api from './api'; | |
export const login = async (username, password) => { | |
const response = await api.post('login', { | |
username, | |
password | |
}); | |
const token = response.data.token; | |
if (token) { | |
localStorage.setItem('user', JSON.stringify(response.data)); | |
} | |
return response.data; | |
}; | |
export const isAuthenticated = () => { | |
const user = localStorage.getItem('user'); | |
if (!user) { | |
return {} | |
} | |
return JSON.parse(user); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import Layout from '../../components/Layout'; | |
const Dashboard = () => { | |
return ( | |
<> | |
<Layout> | |
<h1>Dashboard</h1> | |
</Layout> | |
</> | |
); | |
}; | |
export default Dashboard; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext } from 'react'; | |
import { Link, useHistory } from 'react-router-dom'; | |
import UserContext from '../../services/UserContext'; | |
const Header = () => { | |
const [ currentUser, setCurrentUser ] = useContext(UserContext); | |
const history = useHistory(); | |
const handleLogOut = () => { | |
localStorage.removeItem('user'); | |
setCurrentUser({}); | |
history.push('/'); | |
}; | |
console.log('header', currentUser); | |
return ( | |
<> | |
<header> | |
<nav> | |
<ul> | |
<li> | |
<Link to='/'>Home</Link> | |
</li> | |
<li> | |
<Link to='/products'>Products</Link> | |
</li> | |
<li> | |
<Link to='/users'>Users</Link> | |
</li> | |
</ul> | |
<button | |
type='button' | |
onClick={handleLogOut} | |
> | |
Log out | |
</button> | |
</nav> | |
</header> | |
</> | |
); | |
}; | |
export default Header; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import Header from '../Header'; | |
const Layout = ({ children }) => { | |
return ( | |
<> | |
<Header /> | |
{ children } | |
</> | |
); | |
}; | |
export default Layout; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import { useHistory } from 'react-router-dom'; | |
import { login } from '../../services/AuthService'; | |
const Login = () => { | |
const [ username, setUsername ] = useState(''); | |
const [ password, setPassword ] = useState(''); | |
const history = useHistory(); | |
const onChangeUsername = (e) => { | |
setUsername(e.target.value); | |
}; | |
const onChangePassword = (e) => { | |
setPassword(e.target.value); | |
}; | |
const onSubmit = async (e) => { | |
e.preventDefault(); | |
try { | |
await login(username, password); | |
history.push('/admin'); | |
} catch (error) { | |
console.error('error', error); | |
} | |
}; | |
return ( | |
<> | |
<form onSubmit={onSubmit}> | |
<label htmlFor='username'>Username</label> | |
<input | |
type='text' | |
name='username' | |
value={username} | |
onChange={onChangeUsername} | |
/> | |
<label htmlFor='password'>Password</label> | |
<input | |
type='password' | |
name='password' | |
value={password} | |
onChange={onChangePassword} | |
/> | |
<button type='submit'>Login</button> | |
</form> | |
</> | |
); | |
}; | |
export default Login; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import Layout from '../../components/Layout'; | |
const Products = () => { | |
return ( | |
<> | |
<Layout> | |
<h1>Products</h1> | |
</Layout> | |
</> | |
); | |
}; | |
export default Products; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Switch, Route } from 'react-router-dom'; | |
import Home from './pages/Home'; | |
import Login from './components/Login'; | |
import Dashboard from './components/Dashboard'; | |
import Users from './components/Users'; | |
import Products from './components/Products'; | |
const Routes = () => { | |
return ( | |
<Switch> | |
<Route path='/' exact component={Home} /> | |
<Route path='/login' exact component={Login} /> | |
<Route path='/admin' component={Dashboard} /> | |
<Route path='/users' component={Users} /> | |
<Route path='/products' component={Products} /> | |
</Switch> | |
); | |
}; | |
export default Routes; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, createContext } from 'react'; | |
import { Redirect } from 'react-router-dom'; | |
import { isAuthenticated } from './AuthService'; | |
import Login from '../components/Login'; | |
const UserContext = createContext(); | |
export const UserProvider = ({ children }) => { | |
const [ currentUser, setCurrentUser ] = useState(undefined); | |
useEffect(() => { | |
const checkLoggedIn = async () => { | |
let cuser = isAuthenticated(); | |
if (cuser === null) { | |
localStorage.setItem('user', ''); | |
cuser = ''; | |
} | |
setCurrentUser(cuser); | |
}; | |
checkLoggedIn(); | |
}, []); | |
console.log('usercontext', currentUser); | |
return ( | |
<UserContext.Provider value={[currentUser, setCurrentUser]}> | |
{ currentUser?.token ? children : <Login />} | |
</UserContext.Provider> | |
); | |
}; | |
export default UserContext; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import Layout from '../../components/Layout'; | |
const Users = () => { | |
return ( | |
<> | |
<Layout> | |
<h1>Users</h1> | |
</Layout> | |
</> | |
); | |
}; | |
export default Users; |
what is localStorage and how it is defined ?
what is localStorage and how it is defined ?
It saves the data in the browser
for saving: localStorage.setItem('key_name', data_to_save);
for getting the saved data: localStorage.getItem('key_name');
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dger804 it's a simple implementation with
axios
. Something like: