0
let [auth, setAuth] = useState(null);

    useEffect(() => {
        window.gapi.load('client:auth2', () => { 
            window.gapi.client.init({
                clientId: 'xxx.apps.googleusercontent.com',
                scope: 'email'
            }).then(() => {
                setAuth(window.gapi.auth2.getAuthInstance());
                onAuthChange(auth.isSignedIn.get());
                auth.isSignedIn.listen(onAuthChange);
            });
        });
    }, []);

I am using Google's api for authentication:

https://apis.google.com/js/api.js

I tried to refactor my class component into a functional component using useState, but when using setAuth to assign the value returned by window.gapi.auth2.getAuthInstance(), I get null inside of auth. Is there a reason why setAuth doesn't behave as expected?

I get the following error on the next line:

TypeError: auth is null

Sayaman
  • 1,145
  • 4
  • 14
  • 35
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Raj Jul 18 '20 at 02:00

1 Answers1

0

That's because the the value of auth is not available to your functional component until the next render.

Raj
  • 22,346
  • 14
  • 99
  • 142