Last active
November 16, 2020 12:41
-
-
Save mattiasrunge/258f949587bd6750b0763c164e689ba8 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
/* global gapi */ | |
import React from "react"; | |
const useAuthenticateWithGoogle = (apiKey, clientId, scopes) => { | |
const [ loading, setLoading ] = React.useState(false); | |
const [ authenticated, setAuthenticated ] = React.useState(false); | |
const [ error, setError ] = React.useState(null); | |
React.useEffect(() => { | |
setError(null); | |
setLoading(true); | |
gapi.client.setApiKey(apiKey); | |
gapi.auth.authorize({ | |
"client_id": clientId, | |
scope: scopes, | |
immediate: false | |
}, (authResult) => { | |
setLoading(false); | |
if (authResult && !authResult.error) { | |
setAuthenticated(authResult); | |
} else { | |
setError(authResult?.error ?? "Unknown error"); | |
} | |
}); | |
}, [ apiKey, clientId, scopes ]); | |
return [ | |
authenticated, | |
error, | |
loading | |
]; | |
}; | |
const MyComponent = () => { | |
// Note: If SCOPES is an array, make sure it is declared outside or wrapped with React.useMemo | |
// otherwise it could end up doing strange stuff | |
const [ authenticated, error, loading ] = useAuthenticateWithGoogle(API_KEY, CLIENT_ID, SCOPES); | |
React.useEffect(() => { | |
if (authenticated) { | |
// Do awesome stuff | |
} | |
}, [ authenticated ]); | |
return ( | |
<div>Nice stuff</div> | |
) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment