Created
September 10, 2021 12:05
-
-
Save iffa/9aff6eb522a00b5a1b0dd05ff1ca9bee to your computer and use it in GitHub Desktop.
Hook for redirecting when user is not logged in (React Router v6)
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 { useNavigate } from "react-router-dom"; | |
import useAuth from "./AuthContext"; | |
import React, { useEffect } from "react"; | |
/** | |
* Redirects user to another page if not authenticated. | |
* @param redirectTo Path to redirect to | |
*/ | |
export function useUnauthenticatedRedirect(redirectTo: string = "/") { | |
const navigate = useNavigate(); | |
// user = data | |
// isValidating from swr | |
const { user, isValidating } = useAuth(); | |
useEffect(() => { | |
// redirect if we don't have user data, but also not in the middle of validating data (i.e. attempted once and failed) | |
if (!user && !isValidating) { | |
navigate(redirectTo, { replace: true }); | |
} | |
}, [navigate, user, isValidating, redirectTo]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment