i am trying to build a web game and at first I have this JavaScript “App.js”, where the user can log in via google and if he is logged in, he can log out.
But authInstance.isSignedIn.get() does always return null, after the user is logged in
import logo from './logo.svg';
import './App.css';
import LoginButton from "./components/login";
import LogoutButton from "./components/logout";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import Dashboard from './components/dashboard'; // Dashboard-Seite
import Search from './components/search'; // Dashboard-Seite
import { gapi } from 'gapi-script';
const clientId = "MyApiURL";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false); // State für den Anmeldestatus
useEffect(() => {
function start() {
gapi.client.init({
clientId: clientId,
scope: ""
}).then(() => {
const authInstance = gapi.auth2.getAuthInstance();
// Setzt den Status basierend auf der aktuellen Anmeldung
setIsLoggedIn(authInstance.isSignedIn.get());
// Hört auf Änderungen des Anmeldestatus
authInstance.isSignedIn.listen(setIsLoggedIn);
});
};
gapi.load('client:auth2', start);
}, []);
return (
<Router>
<div className="App">
<Routes>
{/* Login-Route */}
<Route path="/" element={isLoggedIn ? <LogoutButton /> : <LoginButton />} />
<Route path="/search" element={<Search />} /> {/* Route für Search */}
{/* Dashboard-Route nach erfolgreichem Login */}
<Route path="/dashboard" element={<Dashboard isLoggedIn={isLoggedIn} />} />
</Routes>
</div>
</Router>
);
}
export default App;
This is the Login code. When the LoginButton is hit, this is carried out.
import {GoogleLogin} from 'react-google-login';
import { useNavigate } from 'react-router-dom';
import { gapi } from 'gapi-script';
const clientId = "...";
function Login(){
const navigate = useNavigate(); // Initialisiere useNavigate
const onSuccess = (res) => {
console.log("LOGIN SUCCESS! Current user: ", res.profileObj);
navigate('/dashboard');
}
const onFailure = (res) => {
console.log("LOGIN FAILED! res: ", res);
}
return(
<div id = "signInButton">
<GoogleLogin
clientId={clientId}
buttonText="Login"
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={'single_host_origin'}
isSignedIn={true}
/>
</div>
)
}
export default Login;