Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions packages/@react-oauth/google/src/hooks/useGoogleLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ import {
NonOAuthError,
} from '../types';

type WaitFor = (getValue: () => boolean) => Promise<void>;

const waitFor: WaitFor = function waitFor(getValue) {
function _waitFor(getter: () => boolean, cb: () => void): void {
if (!getter()) {
setTimeout(() => {
_waitFor(getter, cb);
}, 0);
} else {
cb();
}
}

return new Promise<void>(resolve => {
_waitFor(getValue, resolve);
});
};

interface ImplicitFlowOptions
extends Omit<TokenClientConfig, 'client_id' | 'scope' | 'callback'> {
onSuccess?: (
Expand Down Expand Up @@ -116,15 +134,17 @@ export default function useGoogleLogin({
}, [clientId, scriptLoadedSuccessfully, flow, scope, state]);

const loginImplicitFlow = useCallback(
(overrideConfig?: OverridableTokenClientConfig) =>
clientRef.current?.requestAccessToken(overrideConfig),
[],
async (overrideConfig?: OverridableTokenClientConfig) => {
await waitFor(() => clientRef.current);
clientRef.current?.requestAccessToken(overrideConfig);
},
[scriptLoadedSuccessfully],
);

const loginAuthCodeFlow = useCallback(
() => clientRef.current?.requestCode(),
[],
);
const loginAuthCodeFlow = useCallback(async () => {
await waitFor(() => clientRef.current);
clientRef.current?.requestCode();
}, []);

return flow === 'implicit' ? loginImplicitFlow : loginAuthCodeFlow;
}