Skip to content

Commit

Permalink
frontend: Add AuthContext.
Browse files Browse the repository at this point in the history
This commit adds an AuthContext exposing the functions to
get and set current auth status. The context is then used in the
App component.
  • Loading branch information
kuv2707 committed Jun 11, 2024
1 parent df7b381 commit 3fa7738
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
9 changes: 8 additions & 1 deletion frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import AppLayout from './pages/AppLayout';
import Error from './pages/Error';
import Game from './pages/Game';
import About from './pages/About';
import { AuthProvider } from './contexts/AuthContext';

const router = createBrowserRouter([
{
Expand All @@ -27,7 +28,13 @@ const router = createBrowserRouter([
]);

function App() {
return <RouterProvider router={router} />;
return (
<AuthProvider>
<>
<RouterProvider router={router} />;
</>
</AuthProvider>
);
}

export default App;
57 changes: 57 additions & 0 deletions frontend/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
ReactElement,
createContext,
useCallback,
useContext,
useState,
} from 'react';

export type User = {
name: string;
email: string;
};

export type AuthContextProps = {
getUser: () => User | null;
login: () => void;
logout: () => void;
isLoggedIn: () => boolean;
};
export const AuthContext = createContext<AuthContextProps>({
getUser: () => null,
login: () => {},
logout: () => {},
isLoggedIn: () => false,
});

// eslint-disable-next-line react-refresh/only-export-components
export function useAuth() {
return useContext(AuthContext);
}

export function AuthProvider({ children }: { children: ReactElement }) {
const [user, setUser] = useState<User | null>(null);

const login = useCallback(() => {
setUser({
name: 'John Doe',
email: '',
});
}, []);

const logout = useCallback(() => {}, []);

const getUser = useCallback(() => {
return user;
}, [user]);

const isLoggedIn = useCallback(() => {
return !!user;
}, [user]);

return (
<AuthContext.Provider value={{ getUser, login, logout, isLoggedIn }}>
{children}
</AuthContext.Provider>
);
}

0 comments on commit 3fa7738

Please sign in to comment.