I am trying to add Google login to my web app. The gapi.auth2.init() succeeds and when I define GoogleAuth as gapi.auth2.getAuthInstance() it doesn't throw an error. However, when I try to run GoogleAuth.signIn() it complains that it is not a function. What am I doing wrong?
This is all within a functional React component:
let GoogleAuth
const googleSignIn = () => {
GoogleAuth.signIn()
.then(() => {
console.log('signed in')
})
.catch(err => {
console.log('failed to sign in: ')
console.log(err)
})
}
window.gapi.load('auth2', () => {
gapi.auth2.init({
client_id: googleClientId
})
.then(() => {
console.log('google auth initialized') // This shows in the console
GoogleAuth = gapi.auth2.getAuthInstance() // This does not throw an error
}, err => {
console.log('google auth failed to initialize')
console.log(err)
})
})
return <GoogleLoginButton text="Log in with Google" onClick={googleSignIn} />
I wait until I see the "google auth initialized" message and then click the button, but it throws the error as described above.
It turns out gapi.auth2.getAuthInstance() returns a promise, not an object (contrary to the docs, thanks Google), so I just had to do this:
gapi.auth2.getAuthInstance()
.then(instance => {
GoogleAuth = instance
}, err => {
console.log(err)
})
Now it works!