การสร้างฟีเจอร์แชตสด
ประยุกต์ความรู้ด้านเรียลไทม์เพื่อสร้างแอปพลิเคชันแชตสดที่ใช้งานได้จริง พร้อมสาธิตการส่งข้อความทันที
การสร้างฟีเจอร์แชตสด เป็นบทเรียน Supabase Backend as a Service ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Supabase Backend as a Service และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Realtime Chat: The Foundation
Welcome to building a live chat! Instant messaging is a perfect example of where realtime capabilities shine.
Users expect their messages to appear instantly without refreshing. Supabase Realtime makes this surprisingly simple.
In this lesson, we'll connect the dots: sending messages to your database and instantly receiving new messages from others.
Designing Your Chat Messages Table
First, we need a place to store our chat messages. A simple table is all it takes!
We'll create a messages table with columns for the message text, who sent it, and when it was sent.
id: Primary Key, unique identifier.text: The message content (type:TEXT).user_id: Who sent the message (type:UUID, linked toauth.users).created_at: When the message was sent (type:TIMESTAMPTZ, default tonow()).
Initializing Supabase Client
To interact with Supabase from your app, you'll need to initialize the client library. This sets up the connection to your project.
Make sure you have your Supabase URL and Anon Key ready. (These are covered in earlier lessons.)
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';
const supabase = createClient(supabaseUrl, supabaseAnonKey);This supabase object will be your gateway to sending and receiving messages.
Sending Messages: The Insert Operation
When a user types a message and hits send, your app needs to store that message in the database.
We'll use the Supabase client's insert() method on our messages table. This adds a new row with the message text and the sender's ID.
It's a straightforward database write operation, just like adding any other data.
Code: Sending a Chat Message
Try running this example. It simulates sending a message to your Supabase messages table.
Remember to replace placeholders with your actual Supabase URL/Key and a valid user_id (e.g., from an authenticated user).
import { createClient } from '@supabase/supabase-js';
// Mock Supabase client for demonstration purposes
// In a real app, use your actual Supabase URL and Anon Key
const supabase = {
from: (tableName) => ({
insert: async (data) => {
console.log(`[DEMO] Attempting to insert into ${tableName}:`);
console.log(JSON.stringify(data, null, 2));
// Simulate a successful response
return { data: data, error: null };
}
})
};
async function sendChatMessage(messageText, senderId) {
const { data, error } = await supabase
.from('messages')
.insert([
{ text: messageText, user_id: senderId }
]);
if (error) {
console.error('Error sending message:', error.message);
} else {
console.log('Message sent successfully:', data);
}
}
// --- Run the example ---
sendChatMessage("Hey there, CoddyKit!", "a1b2c3d4-e5f6-7890-1234-567890abcdef");Receiving Messages in Realtime
Sending messages is only half the story. The magic of live chat is seeing new messages instantly!
Supabase Realtime allows you to subscribe to changes in your database. We'll listen specifically for new INSERT events on our messages table.
When a new message is inserted by any user, your app will receive a notification and can update the chat display.
Code: Subscribing to New Messages
This code sets up a listener for new messages. When a message is inserted, the callback function will run.
The payload.new object contains the full data of the newly inserted message.
import { createClient } from '@supabase/supabase-js';
// Mock Supabase client for demonstration purposes
const supabase = {
channel: (channelName) => ({
on: (eventType, filter, callback) => {
console.log(`[DEMO] Subscribing to channel "${channelName}" for event "${eventType}" with filter:`, JSON.stringify(filter));
// Simulate a message arriving after a delay
setTimeout(() => {
const mockPayload = {
eventType: 'INSERT',
schema: 'public',
table: 'messages',
new: { id: 2, text: 'This is a new realtime message!', user_id: 'another-user-id', created_at: new Date().toISOString() },
old: {}
};
console.log("[DEMO] Simulating new message arrival...");
callback(mockPayload);
}, 3000); // Simulate message arriving after 3 seconds
return {
subscribe: (cb) => {
console.log("[DEMO] Subscription initiated.");
// Simulate successful subscription immediately
cb('SUBSCRIBED');
}
};
}
})
};
// --- Run the example ---
const chatChannel = supabase.channel('messages_channel');
chatChannel
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, (payload) => {
console.log('Realtime: New message received!');
console.log('Message content:', payload.new.text);
console.log('From user:', payload.new.user_id);
// In a real app, you would update your UI here to display the message
})
.subscribe((status) => {
if (status === 'SUBSCRIBED') {
console.log('Successfully subscribed to new messages!');
} else {
console.log('Subscription status:', status);
}
});Displaying Messages in Your UI
Once you receive a new message via the realtime subscription, the next step is to display it in your chat interface.
Typically, you'll take the payload.new object, extract the text, user_id, and created_at, and then dynamically add it to your chat window.
- Create a new chat bubble/element.
- Populate it with the message data.
- Append it to your chat message list.
- Consider scrolling to the bottom automatically for the best user experience!
Adding User Context & Timestamps
A basic chat works, but a good chat shows who sent what and when.
Since our messages table has a user_id, you can fetch user profiles (e.g., username, avatar) to display alongside messages. This might involve a simple join if you're querying historical messages, or fetching user details separately for realtime messages.
The created_at timestamp automatically provided by Supabase is crucial for ordering messages and showing when they were sent.
Quick Check: Chat Flow
You're building a live chat. What are the two primary Supabase client operations you'll use to make messages appear instantly for all users?
Recap: Your Live Chat Feature
You've successfully built the core of a live chat feature!
We covered:
- Designing a simple
messagestable. - Sending new messages by inserting data into Supabase.
- Receiving new messages instantly using Supabase Realtime subscriptions.
- How to integrate these messages into your app's UI.
This pattern of inserting data and subscribing to changes is fundamental for many realtime applications beyond just chat. Keep exploring!
เรียนรู้ Supabase Backend as a Service ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 11
- บทเรียน
- 40
คำถามที่พบบ่อย
บทเรียน “การสร้างฟีเจอร์แชตสด” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างฟีเจอร์แชตสด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Supabase Backend as a Service ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างฟีเจอร์แชตสด”
ประยุกต์ความรู้ด้านเรียลไทม์เพื่อสร้างแอปพลิเคชันแชตสดที่ใช้งานได้จริง พร้อมสาธิตการส่งข้อความทันที คุณปฏิบัติ Supabase Backend as a Service ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Supabase Backend as a Service หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Supabase Backend as a Service บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างฟีเจอร์แชตสด” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Supabase Backend as a Service นี้ได้ไหม
ได้ บทเรียน Supabase Backend as a Service ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทำความเข้าใจการสมัครรับข้อมูลแบบเรียลไทม์
- การสมัครรับการเปลี่ยนแปลงของตาราง
- การสร้างฟีเจอร์แชตสด
- ช่องทางแสดงสถานะและกระจายข้อความ