Skip to content

Instantly share code, notes, and snippets.

@AugustoCalaca
Forked from sibelius/useAuth.tsx
Created February 26, 2020 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AugustoCalaca/a6e858fbca7245c1f099928ca85396d0 to your computer and use it in GitHub Desktop.
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
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