简体   繁体   中英

Why is my callback function never being called?

Im trying to do a login authentication in react js using GoogleOAuth API. In my App im able to log in to different authorized google users but in one part of my code i sen a callback function but it is never being executed.

App.js

import './App.css';
import { useState, useEffect } from 'react';
import { GoogleOAuthProvider } from '@react-oauth/google';
import LoginBtn from './components/atoms/LoginBtn';
import jwt_decode from 'jwt-decode';


function App() {
  const [ user, setUser ] = useState({}) //Store my user data


  function handleCallbackResponse(response){
    var userData = jwt_decode(response.credentials);
    console.log(userData);
    setUser(userData);
  }

  
  useEffect(() => {
    /*global google*/
    google.accounts.id.initialize({
      client_id: "Google Cliente goes here",
      callback: handleCallbackResponse
    });

  }, []); //useEffect will run only if anything inside the empty array  
  
  
  return (

    <GoogleOAuthProvider clientId="My Google client goes here">
      <div className="App">
        <LoginBtn />
      </div>
    </GoogleOAuthProvider>
  );
}

export default App;

So above i pasted my App component with its logic so that you can follow completely. The following is the function not being executed

For any reasons this is never console.loging anything in my console:

function handleCallbackResponse(response){
    var userData = jwt_decode(response.credentials);
    console.log(userData);
    setUser(userData);
  }

The function above is called in the following code of block:

useEffect(() => {
    /*global google*/
    google.accounts.id.initialize({
      client_id: "Google Cliente goes here",
      callback: handleCallbackResponse
    });

  }, []); //useEffect will run only if anything inside the empty array 

At my index.html i pasted the following script to access global google keywords and js objects. Which is between my head tags.

<script src="https://accounts.google.com/gsi/client" async defer></script>

Instead of google.accounts.id, use window.google.accounts.id

window.google.accounts.id.initialize({
client_id: CLIENT_ID,
callback: data => handleCredentialResponse(data),
state_cookie_domain: 'https://example.com',});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM