Skip to content

Instantly share code, notes, and snippets.

@liyaodong
Created July 1, 2022 08:27
Show Gist options
  • Save liyaodong/a80131b1f259bde92b7ea6d2a5462e46 to your computer and use it in GitHub Desktop.
Save liyaodong/a80131b1f259bde92b7ea6d2a5462e46 to your computer and use it in GitHub Desktop.
auth0-react get token outside of react component
// your app.tsx
const {
getAccessTokenSilently,
loginWithRedirect,
user,
isAuthenticated,
isLoading,
} = useAuth0();
useEffect(() => {
if (!isLoading) {
if (!isAuthenticated) {
loginWithRedirect();
return;
}
setAuthTokenGetter(getAccessTokenSilently);
}
}, [isAuthenticated, isLoading]);
// 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