import React from "react"; import { User } from "lucide-react"; import { Card } from "@/components/ui/card"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { supabase } from "@/lib/supabase"; import { formatDistanceToNow } from "date-fns"; interface Message { id: string; phone_number: string; message: string; created_at: string; } export function ConversationList() { const queryClient = useQueryClient(); const { data: messages, isLoading } = useQuery({ queryKey: ['messages'], queryFn: async () => { const { data, error } = await supabase .from('messages') .select('*') .order('created_at', { ascending: false }); if (error) { console.error('Error fetching messages:', error); throw error; } return data as Message[]; }, refetchInterval: 5000 // Refetch every 5 seconds }); // Subscribe to new messages // React.useEffect(() => { // const subscription = supabase // .channel('messages') // .on('postgres_changes', { // event: '*', // schema: 'public', // table: 'messages' // }, () => { // // Trigger a refetch when new messages arrive // queryClient.invalidateQueries({ queryKey: ['messages'] }); // }) // .subscribe(); // return () => { // // subscription.unsubscribe(); // }; // }, [queryClient]); const fetchRecords= async () => { const response = await fetch('/functions/v1/get-messages', { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); const result = await response.json(); console.log('result', result); } React.useEffect(() => { fetchRecords(); }, []); if (isLoading) { return (

Loading conversations...

); } const conversations = messages || []; return (

Conversations

{conversations.length} active
{conversations.map((message) => (

{message.phone_number}

{formatDistanceToNow(new Date(message.created_at), { addSuffix: true })}

{message.message}

))}
); }