MCPcopy Create free account
hub / github.com/WardAnalytics/WardGraph / useActiveSubscription

Function useActiveSubscription

src/services/stripe/subscriptions.tsx:21–80  ·  view source on GitHub ↗
({ enabled }: UserSubscriptionOptions = { enabled: true })

Source from the content-addressed store, hash-verified

19}
20
21export const useActiveSubscription = ({ enabled }: UserSubscriptionOptions = { enabled: true }) => {
22 const [subscription, setSubscription] = useState<Subscription | undefined>(undefined);
23 const [loading, setLoading] = useState(false);
24 const [error, setError] = useState<Error | null>(null);
25
26 const getSubscriptionPrice = async (subscription: Subscription) => {
27 const priceQuery = query(collection(db, "products", subscription.id, "prices"), where("active", "==", true), limit(1));
28
29
30 const priceSnap = await getDocs(priceQuery);
31 if (priceSnap.empty) {
32 throw new Error("No active prices found for subscription");
33 }
34
35 const priceData = priceSnap.docs[0].data();
36 const price: Price = {
37 id: priceSnap.docs[0].id,
38 amount: priceData.unit_amount / 100,
39 };
40
41 subscription.price = price;
42
43 return subscription;
44 }
45
46 const getSubscription = async () => {
47 const queryRef = query(collection(db, "products"), where("active", "==", true));
48 const collectionSnap = await getDocs(queryRef);
49
50 for (const doc of collectionSnap.docs) {
51 const subscriptionObj = doc.data() as Subscription;
52 subscriptionObj.id = doc.id;
53
54 const subscription = await getSubscriptionPrice(subscriptionObj);
55
56 return subscription;
57 }
58
59 return null;
60 }
61
62 useEffect(() => {
63 if (enabled) {
64 setLoading(true);
65
66 getSubscription().then((subscription) => {
67 if (subscription) {
68 setSubscription(subscription);
69 }
70 setLoading(false);
71 }).catch((error) => {
72 setLoading(false);
73 setError(error as Error);
74 });
75 }
76 }, []);
77
78 return { subscription, loading, error };

Callers

nothing calls this directly

Calls 1

getSubscriptionFunction · 0.85

Tested by

no test coverage detected