Skip to main content

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

  1. <RequireAuth> ↔ custom FC Wrapper to Declaratively control Protected Route via useAuth() & <Navigate\> from react-router-dom