From 1fc5a82727f3553667830f7303aaaf8d52b084f2 Mon Sep 17 00:00:00 2001 From: Eva Langerova Date: Tue, 15 Oct 2024 18:41:31 +0200 Subject: [PATCH 1/2] implement protected route in App.jsx, add loading state to useAuth hook --- src/App.jsx | 27 ++++++++++++++++++++++++--- src/api/useAuth.jsx | 8 ++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index ec66a3c..6435cea 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,4 +1,9 @@ -import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; +import { + BrowserRouter as Router, + Routes, + Route, + Navigate, +} from 'react-router-dom'; import { Home, Layout, List, ManageList, About } from './views'; @@ -6,6 +11,16 @@ import { useAuth, useShoppingListData, useShoppingLists } from './api'; import { useStateWithStorage } from './utils'; +function PrivateRoute({ children }) { + const { user, loading } = useAuth(); + + if (loading) { + return
Loading...
; + } + + return user ? children : ; +} + export function App() { const [listPath, setListPath] = useStateWithStorage( 'tcl-shopping-list-path', @@ -38,12 +53,18 @@ export function App() { } /> } + element={ + + + + } /> + + + } /> diff --git a/src/api/useAuth.jsx b/src/api/useAuth.jsx index fdf1966..5f78d34 100644 --- a/src/api/useAuth.jsx +++ b/src/api/useAuth.jsx @@ -29,15 +29,19 @@ export const SignOutButton = () => ( */ export const useAuth = () => { const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); useEffect(() => { - auth.onAuthStateChanged((user) => { + const unsubscribe = auth.onAuthStateChanged((user) => { setUser(user); + setLoading(false); if (user) { addUserToDatabase(user); } }); + + return () => unsubscribe(); }, []); - return { user }; + return { user, loading }; }; From 4bfd54affe82da33a7bea7c474b17b01a7cb583c Mon Sep 17 00:00:00 2001 From: Eva Langerova Date: Tue, 15 Oct 2024 18:43:59 +0200 Subject: [PATCH 2/2] fix text typo in About view --- src/views/About.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/views/About.jsx b/src/views/About.jsx index 67a885b..d7c4621 100644 --- a/src/views/About.jsx +++ b/src/views/About.jsx @@ -37,7 +37,7 @@ export function About() {
  • Share your list with friends, family, colleagues or whomever you - wish. + wish