Created
November 13, 2020 10:43
-
-
Save LuigiClaudio/19e3fe739734845ababe247ce8ad7169 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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