admin管理员组

文章数量:1287246

I'm building a real-time transcript viewer using Svelte 5 and Supabase. I need to subscribe to changes in a JSONB column that contains conversation transcripts.

Here's my current approach:

let transcripts = $state([])
let subscription
onMount(() => {
subscription = supabase
.from('demos')
.on('UPDATE', payload => {
transcripts = payload.new.transcripts
})
.subscribe()
})

However, I'm unsure if this is the optimal way to handle subscriptions with the new runes system. Should I be using $derived or other runes? How do I properly clean up the subscription?

First Attempt:

<script>
let transcripts = $state([]);
let subscription;
onMount(() => {
subscription = supabase
.from('demos')
.on('UPDATE', payload => {
transcripts = payload.new.transcripts;
})
.subscribe();
});
onDestroy(() => {
subscription?.unsubscribe();
});
</script>

This worked but didn't feel idiomatic with Svelte 5's runes. I also tried using $derived:

<script>
let transcripts = $state([]);
let latestPayload = $state(null);
$derived(() => {
if (latestPayload) {
transcripts = latestPayload.new.transcripts;
}
});
onMount(() => {
subscription = supabase
.from('demos')
.on('UPDATE', payload => {
latestPayload = payload;
})
.subscribe();
});
</script>

本文标签: How to properly handle realtime Supabase subscriptions using Svelte 5 runesStack Overflow