subscriptions.ts75 lines, 1.9 KB
| 1 | import { |
| 2 | SubscriptionPlan, |
| 3 | UserSubscriptionResponse, |
| 4 | CheckoutSessionResponse, |
| 5 | CheckoutSessionRequest, |
| 6 | } from "@/lib/api/types"; |
| 7 | import { |
| 8 | getSubscriptionPlans, |
| 9 | getUserSubscription, |
| 10 | createCheckoutSession, |
| 11 | cancelSubscription, |
| 12 | } from "@/lib/api/subscription"; |
| 13 | import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; |
| 14 | |
| 15 | /** |
| 16 | * Hook to fetch all available subscription plans |
| 17 | */ |
| 18 | export function useSubscriptionPlans() { |
| 19 | return useQuery<SubscriptionPlan[]>({ |
| 20 | queryKey: ["subscription-plans"], |
| 21 | queryFn: getSubscriptionPlans, |
| 22 | }); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Hook to fetch the current user's subscription |
| 27 | */ |
| 28 | export function useUserSubscription() { |
| 29 | return useQuery<UserSubscriptionResponse>({ |
| 30 | queryKey: ["user-subscription"], |
| 31 | queryFn: async () => { |
| 32 | console.log("Fetching user subscription data..."); |
| 33 | try { |
| 34 | const data = await getUserSubscription(); |
| 35 | console.log("User subscription response:", data); |
| 36 | return data; |
| 37 | } catch (error) { |
| 38 | console.error("Error fetching user subscription:", error); |
| 39 | throw error; |
| 40 | } |
| 41 | }, |
| 42 | }); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Hook to create a checkout session for subscribing to a plan |
| 47 | */ |
| 48 | export function useCreateCheckoutSession() { |
| 49 | const queryClient = useQueryClient(); |
| 50 | |
| 51 | return useMutation({ |
| 52 | mutationFn: (data: CheckoutSessionRequest) => createCheckoutSession(data), |
| 53 | onSuccess: (data: CheckoutSessionResponse) => { |
| 54 | // Redirect to Stripe checkout |
| 55 | if (data.url && typeof window !== "undefined") { |
| 56 | window.location.href = data.url; |
| 57 | } |
| 58 | }, |
| 59 | }); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Hook to cancel the current user's subscription |
| 64 | */ |
| 65 | export function useCancelSubscription() { |
| 66 | const queryClient = useQueryClient(); |
| 67 | |
| 68 | return useMutation({ |
| 69 | mutationFn: cancelSubscription, |
| 70 | onSuccess: () => { |
| 71 | // Invalidate the user subscription query to refetch the data |
| 72 | queryClient.invalidateQueries({ queryKey: ["user-subscription"] }); |
| 73 | }, |
| 74 | }); |
| 75 | } |