Skip to content

Commit

Permalink
added persistent state -- user wont be signed out after refreshing page
Browse files Browse the repository at this point in the history
  • Loading branch information
Frank-Gu-81 committed Jan 23, 2025
1 parent 80fb28e commit 226b615
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 25 deletions.
24 changes: 18 additions & 6 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import RatingHistory from './components/RatingHistory/RatingHistory';
import Comment from './components/Comment/Comment';
import SearchPage from './components/SearchPage/SearchPage';
import { doc, getDoc, onSnapshot } from 'firebase/firestore';
import { db } from './utilities/firebase';
import { auth, db } from './utilities/firebase';
import { onAuthStateChanged } from 'firebase/auth';
import { set } from 'firebase/database';

// Toggle this to `true` in dev if you want to skip sign-in
const DEV_MODE = false;
Expand All @@ -29,6 +31,19 @@ function App() {
const [profilePic, setProfilePic] = useState(null);
const [friends, setFriends] = useState([]);
const [filteredPost, setFilteredPost] = useState([]);
const [authLoaded, setAuthLoaded] = useState(false);

useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (curUser) => {
setUser(curUser);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
setUserEmail(curUser?.email);
setProfilePic(curUser?.photoURL);
setAuthLoaded(true);
})

return () => unsubscribe();
}, []);

const isAuthenticated = DEV_MODE || user;

Expand Down Expand Up @@ -78,18 +93,15 @@ function App() {


return (
!authLoaded ? <div>Loading...</div> :
<Container className="app-background" maxWidth="sm" disableGutters>
<Router>
<Routes>
{!DEV_MODE ? (
<Route
path="/"
element={
<SignIn
setUser={setUser}
setUserEmail={setUserEmail}
setProfilePic={setProfilePic}
/>
<SignIn />
}
/>
) : (
Expand Down
16 changes: 6 additions & 10 deletions src/components/SignIn/SignIn.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,22 @@ import logo from "../../images/CBLogo.png";
import { Container } from '@mui/material';
import { useNavigate } from "react-router-dom";

import { signInWithGooglePopup } from "../../utilities/firebase";
// import { signInWithGooglePopup } from "../../utilities/firebase";
import { signInWithGoogle } from "../../utilities/firebase";

import { createUserDocIfNotExists } from "../../utilities/createUserDocIfNotExists";

const SignIn = ({ setUser, setUserEmail, setProfilePic }) => {
const SignIn = () => {
const navigate = useNavigate();

const logGoogleUser = async () => {
try {
const response = await signInWithGooglePopup();
const response = await signInWithGoogle();

// 1) store user in React state
setUser(response.user);
setUserEmail(response.user.email);
setProfilePic(response.user.photoURL);

// 2) ensure there's a doc in "users/{uid}"
// 1) ensure there's a doc in "users/{uid}"
await createUserDocIfNotExists(response.user);

// 3) navigate to feed
// 2) navigate to feed
navigate("/feed");
} catch (error) {
console.error("Error signing in with Google: ", error);
Expand Down
21 changes: 12 additions & 9 deletions src/utilities/firebase.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { getAuth, signInWithPopup, GoogleAuthProvider, browserLocalPersistence, setPersistence } from "firebase/auth";
import { collection, getDocs } from "firebase/firestore";
import { get } from "firebase/database";

Expand All @@ -19,12 +19,10 @@ const firebaseConfig = {
// Initialize Firebase
const app = initializeApp(firebaseConfig);

const provider = new GoogleAuthProvider();

export const db = getFirestore(app);
// export const analytics = getAnalytics(app);
export const auth = getAuth(app);
export const signInWithGooglePopup = () => signInWithPopup(auth, provider);
export const provider = new GoogleAuthProvider();

// Only initialize analytics if running in a browser -- this is for dataInsertion.js
// We probably don't need this for the final project
Expand All @@ -33,8 +31,13 @@ if (typeof window !== "undefined") {
analytics = getAnalytics(app);
}

// Example query code:
// const querySnapshot = await getDocs(collection(db, "posts"));
// querySnapshot.forEach((doc) => {
// console.log(doc.id, "=>", doc.data());
// });
export const signInWithGoogle = async () => {
try{
setPersistence(auth, browserLocalPersistence);
const result = await signInWithPopup(auth, provider);
const user = result.user;
return {user};
} catch (error) {
console.error("Error signing in with Google: ", error);
}
}

0 comments on commit 226b615

Please sign in to comment.