Supabase realtime changes in Nuxt

jacobandrewsky

Jakub Andrzejewski

Posted on September 18, 2023

Supabase realtime changes in Nuxt

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Let's stop for a second to explain each step here:

  1. We are importing the RealtimeChannel type to have full type safety and completion.
  2. We are calling client.channel() method on public table called cats.
  3. We are reacting on postgres_changes for all events in public schema for table cats.
  4. After each such event, lets refresh the cats data by refreshCats()
  5. 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>
Enter fullscreen mode Exit fullscreen mode

You can check more details about both Supabase and Realtime channels here

💖 💪 🙅 🚩
jacobandrewsky
Jakub Andrzejewski

Posted on September 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related