useAuth()
↔ async
Custom Hook to get Auth state from Backend/Online API
export default useAuth() {
const [auth, setAuth] = useState(false)
return {
auth,
login() {
return new Promise((res) => {
setAuth(true)
res() // set up actions to login
})
}.
logout() {
return new Promise((res) => {
setAuth(false)
res() // set up actions to logout
})
}
}
}
//const {auth, login, logout} = useAuth()
Example FC
function Page() {
const {login} = useAuth()
function handleLogin() {
login().then(() => navigate(state?.path || "/account"))
}
return ( //...<button onClick={handleLogin}}\>Log in</button\>)
}
References
<RequireAuth>
↔ custom FC Wrapper to Declaratively control Protected Route viauseAuth()
&<Navigate\>
fromreact-router-dom