Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

topaztee commented Dec 17, 2019

(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

This comment has been minimized.

Copy link
Owner Author

gragland commented Dec 17, 2019

@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
You can’t perform that action at this time.