Created
February 26, 2020 14:46
-
-
Save sibelius/d4e04e2bc3624e8e61562ec2f66d4b17 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; | |
}; |
Check relay workshop
Thanks! For reference: https://github.com/sibelius/relay-workshop/blob/master/packages/route/src/useHistory.tsx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi sibelius, Do you by any chance have the possibility to share ../routing/useHistory with me? I expect that it too must implement router.preloadCode and router.preload to work with the issue-tracker example https://github.com/relayjs/relay-examples/tree/master/issue-tracker