Skip to content

Instantly share code, notes, and snippets.

@timReynolds
Created August 25, 2021 09:50
Show Gist options
  • Save timReynolds/46290cfd93b13e80454922643c39c8a3 to your computer and use it in GitHub Desktop.
Save timReynolds/46290cfd93b13e80454922643c39c8a3 to your computer and use it in GitHub Desktop.
Current User React Hook and Context
import React from "react";
import { ICurrentUser } from "../../../types";
import { IUserProfile } from "../../../userProfile/types";
interface ICurrentUserContextProps {
currentUser?: ICurrentUser;
profile?: IUserProfile;
accessToken: () => Promise<string | undefined>;
refetchCurrentUser: () => Promise<void>;
}
const CurrentUserContext = React.createContext<ICurrentUserContextProps>({
currentUser: undefined,
profile: undefined,
accessToken: () => {
return Promise.resolve("");
},
refetchCurrentUser: () => {
return Promise.resolve();
}
});
export default CurrentUserContext;
import gql from "graphql-tag";
import { useQuery } from "react-apollo";
import track, { TrackingProp } from "react-tracking";
import { getAccessToken } from "../../index";
import { ReactChild } from "react";
import CurrentUserContext from "./CurrentUserContext";
const ACCOUNT_QUERY = gql`
query user {
currentUser {
userProfileUid
authenticationUid
profile {
uid
email
phoneNumber
forename
surname
landlordSituation
}
}
}
`;
interface ICurrentUserProps {
tracking?: TrackingProp;
children?: ReactChild;
}
const CurrentUserProvider = (props: ICurrentUserProps) => {
const { tracking } = props;
const { data, refetch, loading } = useQuery(ACCOUNT_QUERY);
if (loading) {
return null;
}
const { currentUser } = data;
if (currentUser && currentUser.profile) {
tracking.trackEvent({
identity: {
forename: currentUser.profile.forename,
surname: currentUser.profile.surname,
email: currentUser.profile.email
}
});
}
return (
<CurrentUserContext.Provider
value={{
currentUser,
profile: data.currentUser ? data.currentUser.profile : null,
accessToken: getAccessToken,
refetchCurrentUser: async () => {
refetch();
}
}}
>
{props.children}
</CurrentUserContext.Provider>
);
};
export default track({})(CurrentUserProvider);
import { useContext } from "react";
import { ICurrentUser } from "../../../types";
import { IUserProfile } from "../../../userProfile/types";
import CurrentUserContext from "./CurrentUserContext";
export interface ICurrentUserProps {
currentUser?: ICurrentUser;
profile?: IUserProfile;
accessToken: () => Promise<string | undefined>;
refetchCurrentUser: () => Promise<void>;
}
export default () => {
return useContext(CurrentUserContext);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment