0Pricing
React Native Academy · บทเรียน

การสมัครรับข้อมูลแบบเรียลไทม์

สมัครรับการเปลี่ยนแปลงฐานข้อมูลด้วย supabase.channel รับฟังเหตุการณ์ INSERT และ UPDATE บนตาราง และอัปเดตสถานะ UI ภายในแบบตอบสนองโดยไม่ต้องคอยเรียกตรวจสอบ

การสมัครรับข้อมูลแบบเรียลไทม์ เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Are Real-Time Subscriptions?

Real-time subscriptions allow your React Native app to receive database changes as they happen, without polling. When another user inserts, updates, or deletes a row, Supabase pushes the change to all subscribed clients over a WebSocket connection.

This is ideal for chat apps, live feeds, collaborative tools, and any feature where multiple users interact with shared data. Supabase's real-time engine is built on PostgreSQL's logical replication and the supabase-js client handles the WebSocket lifecycle for you.

Enabling Real-Time on a Table

Before subscribing to changes, you must enable real-time replication for the table in Supabase. Go to the Supabase dashboard, open Database > Replication, and add the table to the supabase_realtime publication.

You can also do this with SQL: ALTER PUBLICATION supabase_realtime ADD TABLE your_table;. Without this step, your subscription will connect but receive no events, which is a common source of confusion when first setting up real-time.

-- Enable real-time for the 'messages' table
ALTER PUBLICATION supabase_realtime ADD TABLE messages;

-- Verify which tables have real-time enabled:
SELECT tablename FROM pg_publication_tables
WHERE pubname = 'supabase_realtime';

Creating a Channel and Subscribing

Subscriptions in Supabase v2 are created with supabase.channel('channel-name'). You attach one or more event listeners with .on('postgres_changes', filter, callback), then call .subscribe() to start the WebSocket connection.

The filter object specifies the event (INSERT, UPDATE, DELETE, or * for all), the schema, and the table. The callback receives a payload object with the changed data.

const channel = supabase
  .channel('messages-changes')
  .on(
    'postgres_changes',
    { event: '*', schema: 'public', table: 'messages' },
    (payload) => {
      console.log('Change received:', payload);
    }
  )
  .subscribe();

// Unsubscribe when done:
// supabase.removeChannel(channel);

The Payload Structure

The payload object passed to your callback contains the change details:

  • eventType — 'INSERT', 'UPDATE', or 'DELETE'
  • new — the new row data (available for INSERT and UPDATE)
  • old — the previous row data (available for UPDATE and DELETE)
  • schema and table — which table changed

For DELETE events, payload.new is an empty object and payload.old contains the deleted row. For INSERT, payload.old is empty.

supabase
  .channel('messages-changes')
  .on(
    'postgres_changes',
    { event: 'INSERT', schema: 'public', table: 'messages' },
    (payload) => {
      // payload.eventType === 'INSERT'
      // payload.new === { id: '...', text: 'Hello!', user_id: '...' }
      // payload.old === {}
      console.log('New message:', payload.new);
    }
  )
  .subscribe();

Updating State on Real-Time Events

The most common pattern is to update a state array when a real-time event arrives. For INSERT events, append the new row. For UPDATE, replace the matching row. For DELETE, filter the row out.

Be careful to use the functional form of the state setter (setMessages(prev => [...])) to always work with the latest state, since the subscription callback is a closure that captures the state at subscription time.

const [messages, setMessages] = useState([]);

useEffect(() => {
  const channel = supabase
    .channel('messages-live')
    .on('postgres_changes',
      { event: 'INSERT', schema: 'public', table: 'messages' },
      (payload) => {
        setMessages(prev => [payload.new, ...prev]);
      }
    )
    .on('postgres_changes',
      { event: 'DELETE', schema: 'public', table: 'messages' },
      (payload) => {
        setMessages(prev => prev.filter(m => m.id !== payload.old.id));
      }
    )
    .subscribe();

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

Filtering Subscriptions by Column Value

To subscribe only to changes in rows relevant to the current user or room, add a filter string to the event options. The filter syntax is 'column_name=eq.value', similar to PostgREST query syntax.

This reduces unnecessary network traffic on the client and avoids processing changes that are not relevant to the current screen. For example, in a chat app, subscribe only to messages in the current room.

const roomId = 'room-42';

const channel = supabase
  .channel('room-messages')
  .on(
    'postgres_changes',
    {
      event: '*',
      schema: 'public',
      table: 'messages',
      filter: 'room_id=eq.' + roomId,
    },
    (payload) => {
      // Only fires for messages in room-42
      console.log('Room message event:', payload);
    }
  )
  .subscribe();

Broadcast: Real-Time Without a Database

Supabase channels also support Broadcast, which lets you send ephemeral messages to all clients subscribed to the same channel without writing to the database. This is perfect for typing indicators, cursor positions, or transient presence events.

Use .on('broadcast', { event: 'typing' }, callback) to receive broadcast messages and channel.send to send them. Broadcast messages are not stored and do not trigger RLS policies.

const channel = supabase.channel('typing-indicators');

// Listen for typing events
channel.on('broadcast', { event: 'typing' }, (payload) => {
  console.log(payload.payload.username, 'is typing...');
}).subscribe();

// Send a typing event
async function sendTypingIndicator(username: string) {
  await channel.send({
    type: 'broadcast',
    event: 'typing',
    payload: { username },
  });
}

Presence: Tracking Online Users

Presence is a Supabase feature that lets you track which users are currently online and share state between them. Each client tracks its own presence, and the channel aggregates the presence of all connected clients in real time.

This is ideal for showing an online indicator next to user avatars in a chat list or a participants sidebar in a collaborative document.

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

channel
  .on('presence', { event: 'sync' }, () => {
    const state = channel.presenceState();
    console.log('Currently online:', Object.keys(state));
  })
  .subscribe(async (status) => {
    if (status === 'SUBSCRIBED') {
      await channel.track({ user_id: currentUserId, online_at: new Date().toISOString() });
    }
  });

// Untrack when leaving the screen
// await channel.untrack();

Cleaning Up Subscriptions in useEffect

Real-time channels use WebSocket connections. It is critical to clean up by calling supabase.removeChannel(channel) when the component unmounts. If you forget to clean up, you will accumulate WebSocket connections and leak memory.

Return a cleanup function from useEffect that removes the channel. React calls this cleanup automatically when the component unmounts or before the effect re-runs due to dependency changes.

useEffect(() => {
  const channel = supabase
    .channel('my-channel')
    .on('postgres_changes',
      { event: '*', schema: 'public', table: 'messages' },
      handleChange
    )
    .subscribe();

  // Cleanup: remove channel on unmount
  return () => {
    supabase.removeChannel(channel);
  };
}, []); // Run once on mount, clean up on unmount

Building a Real-Time Chat Screen

A real-time chat screen combines an initial useEffect fetch for existing messages with a real-time subscription for new ones. Fetch the last 50 messages on mount, then append new messages as they arrive via INSERT events.

Use an inverted FlatList (inverted prop) so the newest message always appears at the bottom without needing to scroll. Render each message as a row with the sender's avatar and text.

export function ChatScreen({ roomId }: { roomId: string }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    // 1. Fetch existing messages
    supabase
      .from('messages')
      .select('*, sender:profiles(username)')
      .eq('room_id', roomId)
      .order('created_at', { ascending: false })
      .limit(50)
      .then(({ data }) => setMessages(data ?? []));

    // 2. Subscribe to new messages
    const channel = supabase
      .channel('room-' + roomId)
      .on('postgres_changes',
        { event: 'INSERT', schema: 'public', table: 'messages',
          filter: 'room_id=eq.' + roomId },
        (payload) => setMessages(prev => [payload.new, ...prev])
      )
      .subscribe();

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

  return <FlatList inverted data={messages} renderItem={({ item }) =>
    <MessageRow message={item} />
  } />;
}

Subscription Status and Error Handling

The .subscribe() method accepts an optional callback that receives the subscription status. You can use this to show connection indicators in your UI or retry logic when the subscription fails.

Possible status values include 'SUBSCRIBED' (active), 'TIMED_OUT', 'CLOSED', and 'CHANNEL_ERROR'. Always handle error states to give users feedback when real-time functionality is unavailable.

const channel = supabase
  .channel('live-feed')
  .on('postgres_changes',
    { event: '*', schema: 'public', table: 'posts' },
    handleChange
  )
  .subscribe((status) => {
    if (status === 'SUBSCRIBED') {
      setConnectionStatus('Live');
    } else if (status === 'CHANNEL_ERROR') {
      setConnectionStatus('Disconnected');
    } else if (status === 'TIMED_OUT') {
      setConnectionStatus('Reconnecting...');
    }
  });

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: how to subscribe to Postgres changes with supabase.channel, how to filter subscriptions by column value for targeted updates, and how to properly clean up channels on component unmount to avoid WebSocket leaks. Next up we explore integrating Firebase Auth and Firestore as an alternative backend for React Native apps.

คำถามที่พบบ่อย

บทเรียน “การสมัครรับข้อมูลแบบเรียลไทม์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสมัครรับข้อมูลแบบเรียลไทม์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสมัครรับข้อมูลแบบเรียลไทม์”

สมัครรับการเปลี่ยนแปลงฐานข้อมูลด้วย supabase.channel รับฟังเหตุการณ์ INSERT และ UPDATE บนตาราง และอัปเดตสถานะ UI ภายในแบบตอบสนองโดยไม่ต้องคอยเรียกตรวจสอบ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การสมัครรับข้อมูลแบบเรียลไทม์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตั้งค่าไคลเอนต์ Supabase ใน React Native
  2. การยืนยันตัวตนด้วยอีเมลและ OAuth
  3. การสืบค้นฐานข้อมูลด้วยไคลเอนต์ Supabase
  4. การสมัครรับข้อมูลแบบเรียลไทม์
← กลับไปที่ React Native Academy