TechLead
Lección 6 de 8
5 min de lectura
Supabase

Suscripciones en tiempo real

Crea funciones en tiempo real con Postgres Changes y Broadcast de Supabase

Supabase Realtime

Supabase Realtime te permite escuchar cambios en la base de datos, enviar mensajes entre clientes y rastrear presencia de usuarios, todo en tiempo real con WebSockets.

⚡ Funciones de Realtime

  • Postgres Changes: Escucha INSERT, UPDATE, DELETE
  • Broadcast: Envía mensajes entre clientes conectados
  • Presence: Rastrea usuarios online y su estado

Postgres Changes

Suscríbete a cambios en la base de datos en tiempo real:

// Subscribe to all changes on a table
const channel = supabase
  .channel('posts-changes')
  .on(
    'postgres_changes',
    { event: '*', schema: 'public', table: 'posts' },
    (payload) => {
      console.log('Change:', payload)
    }
  )
  .subscribe()

// Subscribe to specific events
const channel = supabase
  .channel('new-posts')
  .on(
    'postgres_changes',
    { event: 'INSERT', schema: 'public', table: 'posts' },
    (payload) => {
      console.log('New post:', payload.new)
    }
  )
  .subscribe()

Filtrar cambios

// Only listen to changes for a specific user
const channel = supabase
  .channel('user-posts')
  .on(
    'postgres_changes',
    {
      event: '*',
      schema: 'public',
      table: 'posts',
      filter: 'user_id=eq.user-123'
    },
    (payload) => {
      console.log('User post changed:', payload)
    }
  )
  .subscribe()

Broadcast

Envía mensajes directamente entre clientes conectados:

// Create a channel
const channel = supabase.channel('room-1')

// Listen for messages
channel.on('broadcast', { event: 'cursor' }, (payload) => {
  console.log('Cursor moved:', payload)
})

// Subscribe to the channel
channel.subscribe((status) => {
  if (status === 'SUBSCRIBED') {
    // Send a message
    channel.send({
      type: 'broadcast',
      event: 'cursor',
      payload: { x: 100, y: 200 }
    })
  }
})

Presence

Rastrea quién está online y su estado actual:

const channel = supabase.channel('online-users')

// Track presence changes
channel.on('presence', { event: 'sync' }, () => {
  const state = channel.presenceState()
  console.log('Online users:', state)
})

channel.on('presence', { event: 'join' }, ({ key, newPresences }) => {
  console.log('User joined:', newPresences)
})

channel.on('presence', { event: 'leave' }, ({ key, leftPresences }) => {
  console.log('User left:', leftPresences)
})

// Subscribe and track your presence
channel.subscribe(async (status) => {
  if (status === 'SUBSCRIBED') {
    await channel.track({
      user_id: 'user-123',
      username: 'john_doe',
      online_at: new Date().toISOString()
    })
  }
})

Hook de Realtime en React

import { useEffect, useState } from 'react'
import { supabase } from './supabase'

function useRealtimePosts() {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    // Fetch initial posts
    supabase.from('posts').select('*').then(({ data }) => {
      setPosts(data || [])
    })

    // Subscribe to changes
    const channel = supabase
      .channel('posts')
      .on(
        'postgres_changes',
        { event: '*', schema: 'public', table: 'posts' },
        (payload) => {
          if (payload.eventType === 'INSERT') {
            setPosts(prev => [...prev, payload.new])
          } else if (payload.eventType === 'DELETE') {
            setPosts(prev => prev.filter(p => p.id !== payload.old.id))
          } else if (payload.eventType === 'UPDATE') {
            setPosts(prev => prev.map(p =>
              p.id === payload.new.id ? payload.new : p
            ))
          }
        }
      )
      .subscribe()

    return () => {
      supabase.removeChannel(channel)
    }
  }, [])

  return posts
}

Limpieza

// Unsubscribe from a channel
await supabase.removeChannel(channel)

// Unsubscribe from all channels
await supabase.removeAllChannels()

💡 Puntos clave

  • • Postgres Changes escucha INSERT/UPDATE/DELETE en la base de datos
  • • Broadcast envía mensajes entre clientes conectados
  • • Presence rastrea usuarios online y su estado
  • • Limpia las suscripciones al desmontar componentes

📚 Más recursos

Continuar Aprendiendo