Last active
June 8, 2022 22:35
-
-
Save barrybtw/7a05dab355d11bc27118ea65718f6f32 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { auth, googleProvider } from "./firebase"; | |
| import { createContext } from "react"; | |
| const AuthContext = createContext(); | |
| const AuthProvider = () => { | |
| // States we can use to check if user is logged in or not or if there is an error or if the user is loading | |
| const [user, setUser] = useState(null); | |
| const [loading, setLoading] = useState(true); | |
| const [error, setError] = useState(null); | |
| useEffect(() => { | |
| // Auth listener | |
| const subscribe = onAuthStateChanged((user) => { | |
| if (user) { | |
| setUser(user); | |
| setLoading(false); | |
| } else { | |
| setUser(null); | |
| setLoading(false); | |
| } | |
| }); | |
| return () => { | |
| // Cleanup function to 'unsubscribe' from the auth listener | |
| subscribe(); | |
| }; | |
| }, []); | |
| // Actions as login and logout etc. | |
| async function signInWithGoogle() { | |
| // Firebase function to sign in with google passing in googleProvider, could replace in Firebase.js with another provider like github etc. | |
| signInWithPopup(auth, googleProvider) | |
| .then((user) => { | |
| console.log("User signed in with Google", user); | |
| }) | |
| .catch((caughtError) => { | |
| console.log("Caught error signing in with Google", caughtError); | |
| }); | |
| } | |
| async function signOut() { | |
| // Firebase function to sign out | |
| await signOut(auth); | |
| // onAuthStateChanged will listen for changes to the user and update the state in the onAuthStateChanged so no need for setUser(null) | |
| } | |
| // Making a collective object for the auth context | |
| const PassingProps = { | |
| user, | |
| loading, | |
| error, | |
| signInWithGoogle, | |
| signOut, | |
| }; | |
| return ( | |
| <AuthContext.Provider value={PassingProps}> | |
| {/* Pass down the value of the user and loading states to the children components */} | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; |
This file contains hidden or 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 { initializeApp } from "firebase"; | |
| import { getAuth, GoogleAuthProvider } from "firebase/auth"; | |
| const config = {}; | |
| const app = initializeApp(config); | |
| const auth = getAuth(app); | |
| const googleProvider = new GoogleAuthProvider(); | |
| export { auth, googleProvider }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment