From 343cd0234e9127b476614647804cf7e7d80c9909 Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Fri, 17 Apr 2026 17:54:04 +0000 Subject: [PATCH] Changes Co-authored-by: domfelipe <53182096+domfelipe@users.noreply.github.com> --- src/hooks/use-subscription-realtime.ts | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/hooks/use-subscription-realtime.ts diff --git a/src/hooks/use-subscription-realtime.ts b/src/hooks/use-subscription-realtime.ts new file mode 100644 index 0000000..d946923 --- /dev/null +++ b/src/hooks/use-subscription-realtime.ts @@ -0,0 +1,42 @@ +"use client"; + +import { useEffect } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { supabase } from "@/integrations/supabase/client"; +import { useAuth } from "@/hooks/use-auth"; + +/** + * Subscribes to realtime changes on the user's subscription row. + * When the payments webhook upserts a subscription, the affected + * queries are invalidated so the UI updates without a page reload. + */ +export function useSubscriptionRealtime() { + const { user } = useAuth(); + const queryClient = useQueryClient(); + + useEffect(() => { + if (!user?.id) return; + + const channel = supabase + .channel(`subscriptions:user:${user.id}`) + .on( + "postgres_changes", + { + event: "*", + schema: "public", + table: "subscriptions", + filter: `user_id=eq.${user.id}`, + }, + () => { + queryClient.invalidateQueries({ queryKey: ["subscription", user.id] }); + queryClient.invalidateQueries({ queryKey: ["has-active-subscription", user.id] }); + queryClient.invalidateQueries({ queryKey: ["plan"] }); + }, + ) + .subscribe(); + + return () => { + supabase.removeChannel(channel); + }; + }, [user?.id, queryClient]); +}