Spaces:
Paused
Paused
File size: 1,688 Bytes
4efde5d | 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 | 'use client';
import { useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { createClient } from '@/lib/supabase/client';
import { threadKeys } from '@/hooks/react-query/threads/keys';
import { Project } from '../app/(dashboard)/projects/[projectId]/thread/_types';
/**
* Hook to subscribe to real-time project updates and invalidate React Query cache
* This ensures the frontend immediately knows when sandbox data is updated
*/
export function useProjectRealtime(projectId?: string) {
const queryClient = useQueryClient();
useEffect(() => {
if (!projectId) return;
const supabase = createClient();
// Subscribe to project changes
const channel = supabase
.channel(`project-${projectId}`)
.on(
'postgres_changes',
{
event: '*', // Listen to all events (INSERT, UPDATE, DELETE)
schema: 'public',
table: 'projects',
filter: `project_id=eq.${projectId}`,
},
(payload) => {
// Check if sandbox data was updated
const newData = payload.new as Project;
const oldData = payload.old as Project;
if (newData?.sandbox && (!oldData?.sandbox ||
JSON.stringify(newData.sandbox) !== JSON.stringify(oldData.sandbox))) {
// Invalidate specific project query
queryClient.invalidateQueries({
queryKey: threadKeys.project(projectId)
});
}
}
)
.subscribe();
// Cleanup subscription
return () => {
supabase.removeChannel(channel);
};
}, [projectId, queryClient]);
}
|