Last active
July 10, 2025 12:31
-
-
Save Bendzae/a997d8113051d2567092e0bdd51dfe4c 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
| // AuthContext.tsx | |
| import React, { createContext, useContext, ReactNode } from 'react'; | |
| import { useAuth0 } from '@auth0/auth0-react'; | |
| interface AuthContextType { | |
| getToken: () => Promise<string | null>; | |
| isAuthenticated: boolean; | |
| isLoading: boolean; | |
| } | |
| const AuthContext = createContext<AuthContextType | undefined>(undefined); | |
| export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => { | |
| const { getAccessTokenSilently, isAuthenticated, isLoading } = useAuth0(); | |
| const getToken = async (): Promise<string | null> => { | |
| if (!isAuthenticated) return null; | |
| try { | |
| return await getAccessTokenSilently(); | |
| } catch { | |
| return null; | |
| } | |
| }; | |
| return ( | |
| <AuthContext.Provider value={{ getToken, isAuthenticated, isLoading }}> | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; | |
| export const useAuth = (): AuthContextType => { | |
| const context = useContext(AuthContext); | |
| if (!context) { | |
| throw new Error('useAuth must be used within an AuthProvider'); | |
| } | |
| return context; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment