Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created February 26, 2020 14:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sibelius/d4e04e2bc3624e8e61562ec2f66d4b17 to your computer and use it in GitHub Desktop.
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
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;
};
@hegelstad
Copy link

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

@sibelius
Copy link
Author

sibelius commented Oct 3, 2020

Check relay workshop

@hegelstad
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment