Skip to content

Instantly share code, notes, and snippets.

@marcosfreitas
Last active December 10, 2022 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcosfreitas/9d10381c53795e2a79aac854562e17db to your computer and use it in GitHub Desktop.
Save marcosfreitas/9d10381c53795e2a79aac854562e17db to your computer and use it in GitHub Desktop.
const useAuth = (): AuthContextInterface => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within a AuthProvider');
}
return context;
};
const PrivateRoute: React.FC<{ children: ReactElement }> = ({ children }) => {
const { authService, isLoading } = useAuth();
return children;
};
export const AppRoutes = () => {
return (
<Routes>
<Route
path="/"
element={
<PrivateRoute>
<Base />
</PrivateRoute>
}
>
<Route index element={<Home />} />
<Route path="dashboard" element={<Home />} />
</Route>
</Routes>
);
};
export const AuthProvider: React.FC<AuthProviderProps> = ({
children,
authService,
}) => {
// Use the useNavigate hook to get the navigate function from the router context
const navigate = useNavigate();
const [user, setUser] = useState({});
const [loading, setLoading] = useState(true);
return (
<AuthContext.Provider
value={{
authService,
user,
isLoading: () => loading,
}}
>
{children}
</AuthContext.Provider>
);
}
const authService = new AuthService({});
function App() {
return (
<BrowserRouter>
<AuthProvider authService={authService}>
<AppRoutes />
</AuthProvider>
</BrowserRouter>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment