테이블 변경 사항 구독하기
특정 데이터베이스 테이블이나 행의 삽입, 업데이트, 삭제를 수신 대기하는 클라이언트 측 코드를 구현합니다.
테이블 변경 사항 구독하기은(는) CoddyKit의 무료 Supabase Backend as a Service 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Supabase Backend as a Service 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Welcome to Live Data!
In the previous lesson, we learned about the idea of realtime data. Now, let's dive into how your app can actually listen for changes happening in your Supabase database!
This means your users can see updates instantly, without refreshing their screen. Think live chat, notifications, or dashboards.
The Realtime Client
Supabase provides a powerful Realtime client that makes listening for database changes super easy. It's built on PostgreSQL's replication features.
- It uses WebSockets for instant communication.
- You'll interact with it through the
supabase.realtimeobject. - It works by connecting to specific 'channels'.
Creating a Channel
Before listening to changes, you need to create a channel. A channel is like a dedicated line for receiving updates from your database.
You specify which table you're interested in, and then you can subscribe to events on that table.
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// Create a channel for the 'messages' table
const messagesChannel = supabase.channel('table-db-changes')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'messages' },
(payload) => {
console.log('Change received!', payload);
}
)
.subscribe();
console.log('Subscribed to messages channel...');
// In a real app, you'd keep this running to listen.
// For this example, we'll just show the setup.
// You'd typically unsubscribe when the component unmounts.
// messagesChannel.unsubscribe();Listening for All Events
The example above uses event: '*'. This is a wildcard that tells Supabase you want to be notified about all types of changes to your specified table.
- INSERT: A new row was added.
- UPDATE: An existing row was modified.
- DELETE: A row was removed.
Each event type will trigger your callback function.
Code: All Table Changes
Let's refine our channel setup to explicitly listen for all event types on a products table. Imagine we're building an inventory app!
Run this code and imagine new products being added, updated, or deleted.
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const productChanges = supabase.channel('product_updates')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'products' },
(payload) => {
console.log('Product change detected:', payload.eventType);
console.log('New data:', payload.new);
console.log('Old data:', payload.old);
}
)
.subscribe();
console.log('Listening for all changes on products table...');
// This script would typically run in a browser or Node.js environment
// where Supabase client is properly initialized and events would stream.
// For this interactive example, it shows the setup.
// In a real scenario, you'd wait for actual database events.
Targeting Specific Events
Sometimes you only care about certain types of changes. For instance, maybe you only want to know when a new item is added, not when it's updated or deleted.
You can specify the event type in your subscription options:
event: 'INSERT'event: 'UPDATE'event: 'DELETE'
Filtering by Row Data
Beyond event types, you can also filter updates based on the data within the rows themselves. This is super powerful for listening to changes on specific records!
Use conditions like eq (equals) or neq (not equals) on column values:
filter: 'id=eq.123'(Listen for changes to row with ID 123)filter: 'status=neq.archived'(Listen for changes where status is NOT archived)
Code: Filtered Changes
Let's set up a subscription that only listens for new products being added (INSERT) AND only if their category is 'electronics'.
Run this and see how specific you can get!
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_ANON_KEY = 'YOUR_ANON_KEY';
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const newElectronics = supabase.channel('new_electronics_channel')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'products',
filter: 'category=eq.electronics' // Filter by category
},
(payload) => {
console.log('New electronic product added:', payload.new.name);
console.log('Details:', payload.new);
}
)
.subscribe();
console.log('Listening for new electronic products...');
// This code demonstrates the filter setup.
// Actual events would be logged if matching data is inserted.
Handling Incoming Data
When an event occurs, your callback function receives a payload object. This object contains all the details about the change:
eventType: 'INSERT', 'UPDATE', or 'DELETE'.new: The new row data (for INSERT/UPDATE).old: The old row data (for UPDATE/DELETE).table,schema: Info about where the change occurred.
This data lets you update your UI or trigger other logic.
Unsubscribing from Changes
It's important to unsubscribe from channels when they are no longer needed. This prevents memory leaks and unnecessary network traffic.
In a React component, you might unsubscribe in the componentWillUnmount or a useEffect cleanup function. Just call .unsubscribe() on your channel object.
const myChannel = supabase.channel('my_channel')
.on(...)
.subscribe();
// Later, when you're done listening:
myChannel.unsubscribe();
console.log('Unsubscribed from my_channel.');Quick Check: Realtime Filters
You want to listen for any updates to the orders table, specifically for orders where the status changes to 'shipped'.
Which options would you use in your on() method?
Recap: Stay Updated!
Great job! You've learned how to harness Supabase Realtime to listen for live database changes.
- You create a channel for a specific table.
- You use
.on('postgres_changes', options, callback)to subscribe. - You can filter by event type (
INSERT,UPDATE,DELETE) and by row data (e.g.,filter: 'column=eq.value'). - Always remember to unsubscribe when a channel is no longer needed.
Next, we'll build a live chat feature using these concepts!
자주 묻는 질문
“테이블 변경 사항 구독하기” 강의는 무료인가요?
네 — “테이블 변경 사항 구독하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Supabase Backend as a Service 강의 전체를 잠금 해제할 수 있습니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.
“테이블 변경 사항 구독하기”에서 뭘 배우나요?
특정 데이터베이스 테이블이나 행의 삽입, 업데이트, 삭제를 수신 대기하는 클라이언트 측 코드를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Supabase Backend as a Service을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Supabase Backend as a Service을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Supabase Backend as a Service은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“테이블 변경 사항 구독하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Supabase Backend as a Service 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Supabase Backend as a Service 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 실시간 구독 이해하기
- 테이블 변경 사항 구독하기
- 실시간 채팅 기능 구축
- 프레즌스 및 브로드캐스트 채널