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
Top comments (2)
Still can not believe that this is so easy.
Will need to implant this functionality into my app later!
You're a life saver!!!!!