Skip to content

Commit

Permalink
fix: header when disabling javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
HYACCCINT committed Sep 13, 2023
1 parent fbaf3a8 commit e7648b5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
2 changes: 1 addition & 1 deletion nextjs-end/src/app/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default async function RootLayout({ children }) {
<html lang="en">

<body>
<Header initialUser={currentUser.toJSON()}/>
<Header initialUser={currentUser?.toJSON()}/>

<main>{children}</main>
</body>
Expand Down
34 changes: 32 additions & 2 deletions nextjs-end/src/components/Header.jsx
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
6 changes: 4 additions & 2 deletions nextjs-end/src/lib/firebase/auth.js
Original file line number Diff line number Diff line change
@@ -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();
Expand Down

0 comments on commit e7648b5

Please sign in to comment.