mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 06:31:13 -05:00
Fix realtime subscription loop
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { RealtimeChannel } from '@supabase/supabase-js';
|
||||
|
||||
@@ -12,6 +12,18 @@ interface UseRealtimeSubmissionsOptions {
|
||||
export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = {}) => {
|
||||
const { onInsert, onUpdate, onDelete, enabled = true } = options;
|
||||
const [channel, setChannel] = useState<RealtimeChannel | null>(null);
|
||||
|
||||
// Use refs to store latest callbacks without triggering re-subscriptions
|
||||
const onInsertRef = useRef(onInsert);
|
||||
const onUpdateRef = useRef(onUpdate);
|
||||
const onDeleteRef = useRef(onDelete);
|
||||
|
||||
// Update refs when callbacks change
|
||||
useEffect(() => {
|
||||
onInsertRef.current = onInsert;
|
||||
onUpdateRef.current = onUpdate;
|
||||
onDeleteRef.current = onDelete;
|
||||
}, [onInsert, onUpdate, onDelete]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
@@ -27,7 +39,7 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions =
|
||||
},
|
||||
(payload) => {
|
||||
console.log('Submission inserted:', payload);
|
||||
onInsert?.(payload);
|
||||
onInsertRef.current?.(payload);
|
||||
}
|
||||
)
|
||||
.on(
|
||||
@@ -39,7 +51,7 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions =
|
||||
},
|
||||
(payload) => {
|
||||
console.log('Submission updated:', payload);
|
||||
onUpdate?.(payload);
|
||||
onUpdateRef.current?.(payload);
|
||||
}
|
||||
)
|
||||
.on(
|
||||
@@ -51,7 +63,7 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions =
|
||||
},
|
||||
(payload) => {
|
||||
console.log('Submission deleted:', payload);
|
||||
onDelete?.(payload);
|
||||
onDeleteRef.current?.(payload);
|
||||
}
|
||||
)
|
||||
.subscribe((status) => {
|
||||
@@ -64,7 +76,7 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions =
|
||||
console.log('Cleaning up submissions realtime subscription');
|
||||
supabase.removeChannel(realtimeChannel);
|
||||
};
|
||||
}, [enabled, onInsert, onUpdate, onDelete]);
|
||||
}, [enabled]);
|
||||
|
||||
return { channel };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user