Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active January 27, 2024 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gragland/d0fa96ced6b1cf0e6f073964573266f4 to your computer and use it in GitHub Desktop.
Save gragland/d0fa96ced6b1cf0e6f073964573266f4 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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
Copy link

(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 of if(auth.user === null)?

@gragland
Copy link
Author

@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