🧠 Lắng nghe thay đổi Realtime từ bảng section trong Supabase

Nếu bạn đang xây dựng một ứng dụng với React hoặc React Native và muốn cập nhật dữ liệu theo thời gian thực khi có thay đổi trong Supabase thì đây là hướng dẫn chi tiết.


📌 Bắt đầu như sau:

  1. Tạo bảng section trong Supabase Database

Ví dụ:

create table section (
  id uuid primary key default gen_random_uuid(),
  title text,
  content text,
  updated_at timestamp with time zone default now()
);

Bật Realtime cho bảng section

  • Truy cập Supabase Dashboard
  • Vào mục Database > Replication
  • Kéo xuống phần Tables, tìm bảng section
  • Bật công tắc Enable Realtime cho bảng đó
Image Chào Nhé

Lắng nghe realtime thay đổi từ bảng section

Tạo file sectionRealtime.ts:

import { supabase } from './supabaseClient'

const channel = supabase
  .channel('realtime:section')
  .on(
    'postgres_changes',
    {
      event: '*', // INSERT | UPDATE | DELETE | * for all
      schema: 'public',
      table: 'section',
    },
    (payload) => {
      console.log('🔥 Change received!', payload)
      const { eventType, new: newData, old: oldData } = payload

      switch (eventType) {
        case 'INSERT':
          console.log('New section added:', newData)
          break
        case 'UPDATE':
          console.log('Section updated:', newData)
          break
        case 'DELETE':
          console.log('Section deleted:', oldData)
          break
      }
    }
  )
  .subscribe()

🎯 Kết hợp với React Component

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

type Section = {
  id: string
  title: string
  content: string
}

export default function SectionList() {
  const [sections, setSections] = useState<Section[]>([])

  useEffect(() => {
    // Initial fetch
    const fetchSections = async () => {
      const { data, error } = await supabase.from('section').select('*')
      if (data) setSections(data)
    }

    fetchSections()

    // Realtime subscription
    const channel = supabase
      .channel('realtime:section')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'section',
        },
        (payload) => {
          if (payload.eventType === 'INSERT') {
            setSections((prev) => [...prev, payload.new])
          }

          if (payload.eventType === 'UPDATE') {
            setSections((prev) =>
              prev.map((item) =>
                item.id === payload.new.id ? payload.new : item
              )
            )
          }

          if (payload.eventType === 'DELETE') {
            setSections((prev) =>
              prev.filter((item) => item.id !== payload.old.id)
            )
          }
        }
      )
      .subscribe()

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

  return (
    <div>
      <h2>📡 Live Sections</h2>
      <ul>
        {sections.map((section) => (
          <li key={section.id}>
            <strong>{section.title}</strong>: {section.content}
          </li>
        ))}
      </ul>
    </div>
  )
}

✅ Kết luận

  • ✅ Bật tính năng Realtime trong Supabase là bắt buộc nếu bạn muốn nghe thay đổi theo thời gian thực.
  • 🔄 Tính năng này cực kỳ hữu ích trong các ứng dụng như bảng chat, hệ thống thông báo, cập nhật đơn hàng, quản lý task,…
  • 🧪 Chỉ cần vài dòng code là bạn có thể cập nhật UI mà không cần refetch dữ liệu toàn bộ.

Bạn có thể áp dụng kỹ thuật này trong cả Next.js, React Native, Astro, hoặc bất kỳ frontend nào hỗ trợ TypeScript/JavaScript.