Created
August 13, 2022 18:40
-
-
Save jmg/df09787d8633999bf0868c9cbaba4bca to your computer and use it in GitHub Desktop.
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 { useEffect, useState } from "react"; | |
import { getAuth } from "@firebase/auth"; | |
import Router from "next/router"; | |
const auth = getAuth() | |
export const AuthGuard = ({ children, redirectUrl }: any) => { | |
const [isLoading, setIsLoading] = useState(true); | |
const [isAuthenticated, setIsAuthenticated] = useState(false); | |
useEffect(() => { | |
const unsubscribe = auth.onAuthStateChanged(user => { | |
setIsLoading(false); | |
setIsAuthenticated(!!user); | |
}); | |
return () => { | |
unsubscribe(); | |
} | |
} , []); | |
if (isLoading) { | |
return null; | |
} | |
if (!isAuthenticated) { | |
Router.push(redirectUrl); | |
} | |
return children; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment