Skip to content

Instantly share code, notes, and snippets.

@iffa
Created September 10, 2021 12:05
Show Gist options
  • Save iffa/9aff6eb522a00b5a1b0dd05ff1ca9bee to your computer and use it in GitHub Desktop.
Save iffa/9aff6eb522a00b5a1b0dd05ff1ca9bee to your computer and use it in GitHub Desktop.
Hook for redirecting when user is not logged in (React Router v6)
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