-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathUserProvider.tsx
More file actions
56 lines (49 loc) · 1.58 KB
/
UserProvider.tsx
File metadata and controls
56 lines (49 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { usePostHog } from "posthog-js/react";
import {
ReactNode,
createContext,
useEffect,
useLayoutEffect,
useState,
} from "react";
import { AbsoluteOverflowLoader } from "@web/components/AbsoluteOverflowLoader";
import { getUserEmail, getUserId } from "./auth.util";
const UserContext = createContext<
{ isLoadingUser: boolean; userId: string } | undefined
>(undefined);
export const UserProvider = ({ children }: { children: ReactNode }) => {
const [userId, setUserId] = useState<string | null>(null);
const [email, setEmail] = useState<string | null>(null);
const [isLoadingUser, setIsLoadingUser] = useState(false);
const posthog = usePostHog();
useLayoutEffect(() => {
const fetchUserData = async () => {
try {
const uid = await getUserId();
const userEmail = await getUserEmail();
setUserId(uid);
setEmail(userEmail);
} catch (e) {
console.error("Failed to get user because:", e);
} finally {
setIsLoadingUser(false);
}
};
void fetchUserData();
}, []);
// Identify user in PostHog when userId and email are available
// Only runs if PostHog is enabled (POSTHOG_HOST and POSTHOG_KEY are set)
useEffect(() => {
if (userId && email && posthog && typeof posthog.identify === "function") {
posthog.identify(email, { email, userId });
}
}, [userId, email, posthog]);
if (isLoadingUser || userId === null) {
return <AbsoluteOverflowLoader />;
}
return (
<UserContext.Provider value={{ userId, isLoadingUser }}>
{children}
</UserContext.Provider>
);
};