From e7648b5c90bd810d5eb173f09b5c19765c39fc4f Mon Sep 17 00:00:00 2001 From: Cynthia Wang Date: Wed, 13 Sep 2023 17:33:41 -0400 Subject: [PATCH] fix: header when disabling javascript --- nextjs-end/src/app/layout.js | 2 +- nextjs-end/src/components/Header.jsx | 34 ++++++++++++++++++++++++++-- nextjs-end/src/lib/firebase/auth.js | 6 +++-- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/nextjs-end/src/app/layout.js b/nextjs-end/src/app/layout.js index 02026786d..0dee17f15 100644 --- a/nextjs-end/src/app/layout.js +++ b/nextjs-end/src/app/layout.js @@ -18,7 +18,7 @@ export default async function RootLayout({ children }) { -
+
{children}
diff --git a/nextjs-end/src/components/Header.jsx b/nextjs-end/src/components/Header.jsx index a5c7b859e..667c39a09 100644 --- a/nextjs-end/src/components/Header.jsx +++ b/nextjs-end/src/components/Header.jsx @@ -1,16 +1,46 @@ 'use client' -import React from "react"; +import React, { useState, useEffect } from "react"; import Link from "next/link"; import { signInWithGoogle, signOut, + onAuthStateChanged } from "@/src/lib/firebase/auth.js"; import { addFakeRestaurantsAndReviews } from "@/src/lib/firebase/firestore.js"; +import { useRouter } from "next/navigation"; +function useUserSession(initialUser) { + // The initialUser comes from the server via a server component + const [user, setUser] = useState(initialUser); + const router = useRouter() + + useEffect(() => { + const unsubscribe = onAuthStateChanged((authUser) => { + setUser(authUser) + }) + + return () => unsubscribe() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + useEffect(() => { + onAuthStateChanged((authUser) => { + if (user === undefined) return + + // refresh when user changed to ease testing + if (user?.email !== authUser?.email) { + router.refresh() + } + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [user]) + + return user; +} export default function Header({initialUser}) { - const user = initialUser ; + const user = useUserSession(initialUser) ; const handleSignOut = event => { event.preventDefault(); diff --git a/nextjs-end/src/lib/firebase/auth.js b/nextjs-end/src/lib/firebase/auth.js index 380b276dc..cc0380648 100644 --- a/nextjs-end/src/lib/firebase/auth.js +++ b/nextjs-end/src/lib/firebase/auth.js @@ -1,12 +1,14 @@ import { GoogleAuthProvider, signInWithPopup, + onAuthStateChanged as _onAuthStateChanged, } from "firebase/auth"; import { auth } from "@/src/lib/firebase/firebase"; - - +export function onAuthStateChanged(cb) { + return _onAuthStateChanged(auth, cb); +} export async function signInWithGoogle() { const provider = new GoogleAuthProvider();