I'm using https://github.com/anthonyjgrove/react-google-login for auth in my React app. Everything's working except when I close all my tabs and return to my site (within seconds, not even that long), I have to sign in again... How can I persist the login for some amount of time?
Here's my current setup:
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_OAUTH_CLIENT_ID}
buttonText='Continue with Google'
onSuccess={handleGoogleOAuthResponse}
onFailure={handleError}
isSignedIn={true}
prompt='consent'
accessType='offline'
redirectUri={process.env.REACT_APP_FRONT_END_BASE_URL}
/>
const handleGoogleOAuthResponse = ({ accessToken, profileObj }) => {
postRequest('rest-auth/google/', null, { 'access_token': accessToken }) // backend in Django
.then(({ access_token, refresh_token, user }) => {
setAccessToken(access_token); // these are just local states
setRefreshToken(refresh_token);
setProfile(profileObj);
setError(null);
})
.catch(error => {
setError(error);
});
};
const handleError = (error, details) => {
setError(`${error}: ${details}`);
}
The issue is using just the ephemeral state, which gets lost on page reload (and even every time component unmounts) as it is in-memory only. One quick solution would be to also store your token in a
localStorage:With tokens stored, we need to load them as well upon next start of the app, which can be done like this:
or used as initial state in the
useStatehooks: