Created
July 1, 2022 08:27
-
-
Save nothingrealhappen/a80131b1f259bde92b7ea6d2a5462e46 to your computer and use it in GitHub Desktop.
auth0-react get token outside of react component
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
// your app.tsx | |
const { | |
getAccessTokenSilently, | |
loginWithRedirect, | |
user, | |
isAuthenticated, | |
isLoading, | |
} = useAuth0(); | |
useEffect(() => { | |
if (!isLoading) { | |
if (!isAuthenticated) { | |
loginWithRedirect(); | |
return; | |
} | |
setAuthTokenGetter(getAccessTokenSilently); | |
} | |
}, [isAuthenticated, isLoading]); |
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
// your network instance file | |
let authTokenGetter; | |
export const setAuthTokenGetter = (fn) => { | |
authTokenGetter = fn; | |
}; | |
export async function getAuthToken(): Promise<string | null> { | |
return new Promise((res, rej) => { | |
const getToken = async () => { | |
if (authTokenGetter) { | |
const accessToken = await authTokenGetter(); | |
if (!accessToken) { | |
rej(null); | |
} | |
res(`Bearer ${accessToken}`); | |
} | |
setTimeout(() => { | |
getToken(); | |
}, 500); | |
}; | |
return getToken(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment