Last active
November 11, 2019 21:06
-
-
Save YajJackson/21ee43992694cc5a15e56e4c9f1cb0ec to your computer and use it in GitHub Desktop.
React Context Demo
This file contains hidden or 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, useContext, createContext } from 'react' | |
const UserContext = createContext() | |
const Login = ({ onLogin }) => { | |
const [name, setName] = useState('') | |
const [pass, setPass] = useState('') | |
return ( | |
<form onSubmit={() => onLogin({ name, pass })}> | |
<input | |
type="text" | |
onChange={({ target }) => setName(target.value)} | |
/> | |
<input | |
type="password" | |
onChange={({ target }) => setPass(target.value)} | |
/> | |
<button type="submit">Login</button> | |
</form> | |
) | |
} | |
const Home = ({ onLogout }) => { | |
const user = useContext(UserContext) | |
return ( | |
<div> | |
<h1>Logged in</h1> | |
<p>{user.name}</p> | |
<button | |
onClick={() => { | |
localStorage.clear() | |
onLogout() | |
}} | |
> | |
Sign Out | |
</button> | |
</div> | |
) | |
} | |
function App() { | |
const [user, setUser] = useState(JSON.parse(localStorage.getItem('User'))) | |
/* | |
useEffect(() => { | |
const updateUser = setInterval( | |
() => setUser({ name: parseInt(Math.random() * 100) }), | |
1000, | |
) | |
return () => { | |
clearInterval(updateUser) | |
} | |
}, []) | |
*/ | |
return user ? ( | |
<UserContext.Provider value={user}> | |
<Home onLogout={() => setUser(null)} /> | |
</UserContext.Provider> | |
) : ( | |
<Login | |
onLogin={u => { | |
localStorage.setItem('User', JSON.stringify(u)) | |
setUser(u) | |
}} | |
/> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment