-
-
Save AugustoCalaca/a6e858fbca7245c1f099928ca85396d0 to your computer and use it in GitHub Desktop.
useAuth hook to handle authentication, use @inline to consume Relay/GraphQL data outside components
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 { graphql, readInlineData } from 'react-relay'; | |
import { useHistory } from '../routing/useHistory'; | |
import { useAuth_user } from './__generated__/useAuth_user.graphql'; | |
const useAuthFragment = graphql` | |
fragment useAuth_user on User @inline { | |
id | |
name | |
} | |
`; | |
export const useAuth = (userRef: useAuth_user) => { | |
const history = useHistory(); | |
const user = readInlineData<useAuth_user>(useAuthFragment, userRef); | |
const isAuthenticated = !!user; | |
useEffect(() => { | |
if (!isAuthenticated) { | |
history.push('/auth/login'); | |
} | |
}); | |
return isAuthenticated; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment