Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useEffect } from 'react';
import { get } from 'lodash';
import { navigate } from 'gatsby';
import { useLoading } from '@luigiclaudio/ga-baseline-ui/helpers';
import { Identity } from '@luigiclaudio/ga-auth-theme';
const useUser = () => {
const { user, getFreshJWT, logoutUser } = Identity.useIdentityContext();
const [isLoading, load] = useLoading();
const tokenObject = get(user, 'token');
const tokenExpires = get(user, 'token.expires_at');
const nowDate = Date.now();
useEffect(() => {
if (tokenExpires && tokenExpires < nowDate) {
load(getFreshJWT())
.then((res) => {
// eslint-disable-next-line no-console
console.log('res', res);
return res;
})
.catch((err) => {
if (user) {
load(logoutUser())
.then((res) => {
// eslint-disable-next-line no-console
console.log('res', JSON.stringify(res));
return res;
})
.catch((logoutError) => {
// eslint-disable-next-line no-console
console.log('logoutError', logoutError);
return logoutError;
});
} else {
// eslint-disable-next-line no-console
console.log('else navigate');
navigate('/signIn');
}
// eslint-disable-next-line no-console
console.log('err', JSON.stringify(err));
return err;
});
}
if (user && !tokenObject) {
load(logoutUser())
.then(() => {
navigate('/signIn');
})
.catch((err) => {
// eslint-disable-next-line no-console
console.log('logoutError', err);
return err;
});
}
}, [getFreshJWT, nowDate, load, tokenObject]);
if (isLoading) {
// eslint-disable-next-line no-console
console.log('useUser loading');
}
return [user, isLoading];
};
export default useUser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment