Skip to content

Instantly share code, notes, and snippets.

@AugustoCalaca
Forked from gsasouza/useAuth.js
Created March 5, 2020 21:51
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/70eb5bd61cad9e9684223c3d8251e01b to your computer and use it in GitHub Desktop.
Save AugustoCalaca/70eb5bd61cad9e9684223c3d8251e01b to your computer and use it in GitHub Desktop.
Relay hook to handle authenticantion
import { ROOT_ID } from 'relay-runtime';
import { useRelayEnvironment } from 'react-relay/hooks';
import { useLocation, useHistory } from 'react-router-dom';
import { commitLocalUpdate } from 'react-relay'
import { useMutation } from 'relay-hooks/lib';
import { AuthUserMutation } from 'mutations/AuthUserMutation';
export const TOKEN_KEY = 'KEY';
export const useAuthUser = () => {
const environment = useRelayEnvironment();
const loginUpdater = store => {
const me = store.getRootField('AuthUser').getLinkedRecord('me');
store.get(ROOT_ID).setLinkedRecord(me, 'me');
};
const onCompletedLogin = data => {
const { AuthUser } = data;
const { token } = AuthUser;
localStorage.setItem(TOKEN_KEY, token);
};
const [mutate] = useMutation(AuthUserMutation, {
onCompleted,
updater: loginUpdater,
});
const authUser = ({ email, password }) =>
mutate({ variables: { input: { email, password } } });
const logoffUpdater = store => {
const me = store.get(ROOT_ID).getLinkedRecord('me');
return store.delete(me.getDataID());
};
const logoffUser = () => {
localStorage.removeItem(TOKEN_KEY);
commitLocalUpdate(environment, logoffUpdater);
}
return { authUser, logoffUser };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment