Supabase realtime changes in Nuxt
Jakub Andrzejewski
Posted on September 18, 2023
When working with databases, I always find it difficult to create a mechanism that would allow to listen to changes on the database records. And this is such a useful functionality.
Let's imagine that our Frontend application can refresh the list of items when any of them changes in the database. That would have been awesome.
Thankfully, once again Supabase is there to help in the easiest way possible!
Code
Let's say that we have a table in our Supabase dashboard named cats
and we are fetching them like this:
<script setup lang="ts">
const client = useSupabaseClient()
const { data: cats, refresh: refreshCats } = await useAsyncData('cats', async () => {
const { data } = await client.from('cats').select('name')
return data
})
</script>
This is quite a normal approach to fetching data. But how could we listen to the changes and refresh our cats data once there is a change in Supabase?
Let's take a look at the following code sample:
<script setup lang="ts">
import type { RealtimeChannel } from '@supabase/supabase-js'
let realtimeChannel: RealtimeChannel
onMounted(() => {
realtimeChannel = client.channel('public:cats').on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'cats' },
() => refreshCats()
)
realtimeChannel.subscribe()
})
</script>
Let's stop for a second to explain each step here:
- We are importing the
RealtimeChannel
type to have full type safety and completion. - We are calling
client.channel()
method on public table calledcats
. - We are reacting on
postgres_changes
for all events in public schema for table cats. - After each such event, lets refresh the cats data by
refreshCats()
- We also subscribe to this realtimeChannel.
This allows us to listen for these changes and react for them in our Frontend.
Finally, remember to unsubscribe whet the user left the page:
<script setup lang="ts">
onUnmounted(() => {
client.removeChannel(realtimeChannel)
})
</script>
You can check more details about both Supabase and Realtime channels here
Posted on September 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.