Skip to content

Commit

Permalink
implement protected route in App.jsx, add loading state to useAuth hook
Browse files Browse the repository at this point in the history
  • Loading branch information
eva-lng committed Oct 15, 2024
1 parent e456994 commit 1fc5a82
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 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 };
};

0 comments on commit 1fc5a82

Please sign in to comment.