Last active
December 10, 2022 22:58
-
-
Save marcosfreitas/9d10381c53795e2a79aac854562e17db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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