'Google Oauth in functional components / Uncaught TypeError: Cannot read properties of undefined
I beg your assistance on this. I'm using react v16.13.1 and I have a class component which I want to convert to functional component. My goal was to implement a google authenticate feature using functional components.
Should all class property be substitued by an State? this.auth I've converted it to authState.
My functional component code returns this error from time to time. I assume this an asyncrony error and I should put an async function and its await inside the useEffect?
functional component returns this error Thanks in advance for your time.
A. Class component
import React, { Component } from "react"
import { Link } from "react-router-dom"
class GoogleAuthButton extends Component {
state = { isSignedIn: null }
componentDidMount() {
window.gapi.load("auth2", () => {
window.gapi.auth2
.init({
client_id: process.env.REACT_APP_GAUTH2_CLIENT_ID,
scope: "email",
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance()
// updating state so component will re-render
this.setState({ isSignedIn: this.auth.isSignedIn.get() })
})
})
}
retrieveUserStatus() {
if (this.state.isSignedIn === null) {
return "UNKNOWN"
} else if (this.state.isSignedIn) {
return "SIGNED IN"
} else {
return "NOT SIGNED IN"
}
}
render() {
return (
<Link to="/" className="item">
<div>Status: {this.retrieveUserStatus()}</div>
</Link>
)
}
}
export default GoogleAuth
B. Functional component
import React, { useState, useEffect } from 'react';
const GoogleAuthButton = () => {
const [isSignedInState, isSignedInSetState] = useState({ isSignedIn: null });
const [authState, setAuthState] = useState({});
useEffect(()=> {
// the following line arises the error:
window.gapi.load("auth2", () => {
window.gapi.auth2
.init({
client_id: process.env.REACT_APP_CLIENT_ID,
scope: "email",
})
.then(() => {
//gapi.auth2 becomes an state of our function component
setAuthState(window.gapi.auth2.getAuthInstance());
// update state so that component will re-render
isSignedInSetState({ isSignedIn: authState.isSignedIn.get() });
})
} )
},[])
// updates auth state to current auth status.It's triggered when authentication status changes
const onAuthChange = () => {
isSignedInSetState(authState.isSignedIn.get())
}
console.log("authentication", authState)
return (
<div>is the user signed in? {isSignedInState}</div>
)
}
I've added the google auth script in: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- GoogleAuth:-->
**<script src="https://apis.google.com/js/platform.js"></script>**
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|