Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protected routes #65

Merged
merged 2 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading