Skip to content

Commit

Permalink
Merge pull request #65 from the-collab-lab/el-protected-routes
Browse files Browse the repository at this point in the history
Protected routes
  • Loading branch information
eva-lng authored Oct 16, 2024
2 parents e456994 + 4bfd54a commit 4ed1c09
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
27 changes: 24 additions & 3 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
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';

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

import { useStateWithStorage } from './utils';

function PrivateRoute({ children }) {
const { user, loading } = useAuth();

if (loading) {
return <div>Loading...</div>;
}

return user ? children : <Navigate to="/" />;
}

export function App() {
const [listPath, setListPath] = useStateWithStorage(
'tcl-shopping-list-path',
Expand Down Expand Up @@ -38,12 +53,18 @@ export function App() {
<Route path="/about" element={<About />} />
<Route
path="/list"
element={<List data={data} lists={lists} listPath={listPath} />}
element={
<PrivateRoute>
<List data={data} lists={lists} listPath={listPath} />
</PrivateRoute>
}
/>
<Route
path="/manage-list"
element={
<ManageList listPath={listPath} userId={userId} data={data} />
<PrivateRoute>
<ManageList listPath={listPath} userId={userId} data={data} />
</PrivateRoute>
}
/>
</Route>
Expand Down
8 changes: 6 additions & 2 deletions src/api/useAuth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
};
2 changes: 1 addition & 1 deletion src/views/About.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function About() {
</li>
<li>
Share your list with friends, family, colleagues or whomever you
wish.
wish
</li>
</ol>
</section>
Expand Down

0 comments on commit 4ed1c09

Please sign in to comment.