-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuseUser.tsx
86 lines (73 loc) · 2.4 KB
/
useUser.tsx
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { useEffect, useState, createContext, useContext } from "react";
import {
useUser as useSupaUser,
useSessionContext,
User,
} from "@supabase/auth-helpers-react";
import { UserDetails, Subscription } from "@/types";
type UserContextType = {
accessToken: string | null;
user: User | null;
userDetails: UserDetails | null;
isLoading: boolean;
subscription: Subscription | null;
};
export const UserContext = createContext<UserContextType | undefined>(
undefined
);
export interface Props {
[propName: string]: any;
}
export const MyUserContextProvider = (props: Props) => {
const {
session,
isLoading: isLoadingUser,
supabaseClient: supabase,
} = useSessionContext();
const user = useSupaUser();
const accessToken = session?.access_token ?? null;
const [isLoadingData, setIsloadingData] = useState(false);
const [userDetails, setUserDetails] = useState<UserDetails | null>(null);
const [subscription, setSubscription] = useState<Subscription | null>(null);
const getUserDetails = () => supabase.from("users").select("*").single();
const getSubscription = () =>
supabase
.from("subscriptions")
.select("*, prices(*, products(*))")
.in("status", ["trialing", "active"])
.single();
useEffect(() => {
if (user && !isLoadingData && !userDetails && !subscription) {
setIsloadingData(true);
Promise.allSettled([getUserDetails(), getSubscription()]).then(
(results) => {
const userDetailsPromise = results[0];
const subscriptionPromise = results[1];
if (userDetailsPromise.status === "fulfilled")
setUserDetails(userDetailsPromise.value.data as UserDetails);
if (subscriptionPromise.status === "fulfilled")
setSubscription(subscriptionPromise.value.data as Subscription);
setIsloadingData(false);
}
);
} else if (!user && !isLoadingUser && !isLoadingData) {
setUserDetails(null);
setSubscription(null);
}
}, [user, isLoadingUser]);
const value = {
accessToken,
user,
userDetails,
isLoading: isLoadingUser || isLoadingData,
subscription,
};
return <UserContext.Provider value={ value } {...props} />;
};
export const useUser = () => {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error(`useUser must be used within a MyUserContextProvider.`);
}
return context;
};