Last active
January 27, 2024 16:36
-
-
Save gragland/d0fa96ced6b1cf0e6f073964573266f4 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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 Dashboard from "./Dashboard.js"; | |
import Loading from "./Loading.js"; | |
import { useRequireAuth } from "./use-require-auth.js"; | |
function DashboardPage(props) { | |
const auth = useRequireAuth(); | |
// If auth is null (still fetching data) | |
// or false (logged out, above hook will redirect) | |
// then show loading indicator. | |
if (!auth) { | |
return <Loading />; | |
} | |
return ( | |
<Dashboard auth={auth} /> | |
); | |
} | |
// Hook (use-require-auth.js) | |
import { useEffect } from "react"; | |
import { useAuth } from "./use-auth.js"; | |
import { useRouter } from "./use-router.js"; | |
function useRequireAuth(redirectUrl = '/signup'){ | |
const auth = useAuth(); | |
const router = useRouter(); | |
// If auth.user is false that means we're not | |
// logged in and should redirect. | |
useEffect(() => { | |
if (auth.user === false){ | |
router.push(redirectUrl); | |
} | |
}, [auth, router]); | |
return auth; | |
} |
@topaztee that’s because false means the user is logged out, whereas null means we’re still loading their authentication status. We only want to redirect once we know they are logged out.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(in use-auth.tx)
Isnt auth.user initially set at
const [user, setUser] = useState(null);
so why it the check
if (auth.user === false){
instaed ofif(auth.user === null)?