Skip to content

Commit 4ed1c09

Browse files
authored
Merge pull request #65 from the-collab-lab/el-protected-routes
Protected routes
2 parents e456994 + 4bfd54a commit 4ed1c09

File tree

3 files changed

+31
-6
lines changed

3 files changed

+31
-6
lines changed

src/App.jsx

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
1-
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
1+
import {
2+
BrowserRouter as Router,
3+
Routes,
4+
Route,
5+
Navigate,
6+
} from 'react-router-dom';
27

38
import { Home, Layout, List, ManageList, About } from './views';
49

510
import { useAuth, useShoppingListData, useShoppingLists } from './api';
611

712
import { useStateWithStorage } from './utils';
813

14+
function PrivateRoute({ children }) {
15+
const { user, loading } = useAuth();
16+
17+
if (loading) {
18+
return <div>Loading...</div>;
19+
}
20+
21+
return user ? children : <Navigate to="/" />;
22+
}
23+
924
export function App() {
1025
const [listPath, setListPath] = useStateWithStorage(
1126
'tcl-shopping-list-path',
@@ -38,12 +53,18 @@ export function App() {
3853
<Route path="/about" element={<About />} />
3954
<Route
4055
path="/list"
41-
element={<List data={data} lists={lists} listPath={listPath} />}
56+
element={
57+
<PrivateRoute>
58+
<List data={data} lists={lists} listPath={listPath} />
59+
</PrivateRoute>
60+
}
4261
/>
4362
<Route
4463
path="/manage-list"
4564
element={
46-
<ManageList listPath={listPath} userId={userId} data={data} />
65+
<PrivateRoute>
66+
<ManageList listPath={listPath} userId={userId} data={data} />
67+
</PrivateRoute>
4768
}
4869
/>
4970
</Route>

src/api/useAuth.jsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,19 @@ export const SignOutButton = () => (
2929
*/
3030
export const useAuth = () => {
3131
const [user, setUser] = useState(null);
32+
const [loading, setLoading] = useState(true);
3233

3334
useEffect(() => {
34-
auth.onAuthStateChanged((user) => {
35+
const unsubscribe = auth.onAuthStateChanged((user) => {
3536
setUser(user);
37+
setLoading(false);
3638
if (user) {
3739
addUserToDatabase(user);
3840
}
3941
});
42+
43+
return () => unsubscribe();
4044
}, []);
4145

42-
return { user };
46+
return { user, loading };
4347
};

src/views/About.jsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export function About() {
3737
</li>
3838
<li>
3939
Share your list with friends, family, colleagues or whomever you
40-
wish.
40+
wish
4141
</li>
4242
</ol>
4343
</section>

0 commit comments

Comments
 (0)