Bird
Raised Fist0
Supabasecloud~10 mins

Subscribing to database changes in Supabase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Subscribing to database changes
Start Subscription
↓
Listen to DB changes
↓
DB event occurs
↓
Receive event data
↓
Trigger callback function
↓
Process event data
↓
Continue listening or Stop
This flow shows how a subscription listens for database changes, receives events, and processes them continuously.
Execution Sample
Supabase
const subscription = supabase
  .from('messages')
  .on('INSERT', payload => console.log('New message:', payload))
  .subscribe();
This code subscribes to new rows inserted into the 'messages' table and logs the new message data.
Process Table
StepActionEventCallback TriggeredOutput
1Start subscription to 'messages' INSERT eventsNoneNoSubscription active
2Database inserts new row in 'messages'INSERTYesLogs: New message: {new row data}
3Database inserts another new rowINSERTYesLogs: New message: {new row data}
4No new database eventsNoneNoWaiting for events
5Unsubscribe from eventsNoneNoSubscription stopped
💡 Subscription stops when unsubscribe is called or connection closes
Status Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
subscriptionundefinedactive subscription objectactive subscription objectactive subscription objectactive subscription objectnull (unsubscribed)
eventnonenoneINSERT event dataINSERT event datanonenone
callbackTriggeredfalsefalsetruetruefalsefalse
Key Moments - 3 Insights
Why does the callback function run only after a database event?
Because the subscription listens for specific events (like INSERT). The callback triggers only when such an event occurs, as shown in execution_table rows 2 and 3.
What happens if no database changes occur after subscribing?
The subscription stays active but the callback does not run, waiting silently for events. See execution_table row 4.
How do we stop listening to database changes?
By calling unsubscribe on the subscription object, which stops event delivery and sets subscription to null, as in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 2?
ASubscription active
BWaiting for events
CLogs: New message: {new row data}
DSubscription stopped
💡 Hint
Check the 'Output' column in execution_table row 2
At which step does the subscription stop listening to database changes?
AStep 5
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Action' and 'Output' columns in execution_table row 5
If no new INSERT events happen, what happens to the callbackTriggered variable after Step 4?
AIt becomes true
BIt stays false
CIt becomes null
DIt resets to undefined
💡 Hint
See variable_tracker row for callbackTriggered after Step 4
Concept Snapshot
Subscribe to database changes with supabase:
- Use .from('table').on('EVENT', callback).subscribe()
- EVENT can be INSERT, UPDATE, DELETE
- Callback runs only when event occurs
- Use subscription.unsubscribe() to stop
- Keeps listening until unsubscribed or disconnected
Full Transcript
Subscribing to database changes with Supabase means setting up a listener for specific events like new rows inserted. When you start a subscription, it waits silently until the database triggers an event. Once an event happens, the callback function runs with the event data. This process repeats for every matching event. You can stop listening anytime by unsubscribing. This lets your app react live to database updates without constantly checking.

Practice

(1/5)
1. What does subscribing to database changes in Supabase help your app do?
easy
A. Keep app data live and updated automatically
B. Manually refresh data by reloading the page
C. Store data permanently on the client device
D. Encrypt data before sending to the database

Solution

  1. Step 1: Understand the purpose of subscriptions

    Subscriptions listen for database changes and update the app data live.
  2. Step 2: Compare options with subscription benefits

    Only Keep app data live and updated automatically describes automatic live updates, matching subscription behavior.
  3. Final Answer:

    Keep app data live and updated automatically -> Option A
  4. Quick Check:

    Subscriptions = live data updates [OK]
Hint: Subscriptions keep data live without manual refresh [OK]
Common Mistakes:
  • Thinking subscriptions store data locally
  • Confusing subscriptions with manual refresh
  • Assuming subscriptions encrypt data
2. Which of the following is the correct syntax to subscribe to INSERT events on the 'messages' table in Supabase?
easy
A. supabase.from('messages').on('UPDATE', callback).subscribe()
B. supabase.from('messages').on('INSERT', callback).subscribe()
C. supabase.table('messages').listen('INSERT', callback).subscribe()
D. supabase.listen('messages').on('INSERT', callback).subscribe()

Solution

  1. Step 1: Recall correct Supabase subscription syntax

    The correct method is supabase.from('table').on('EVENT', callback).subscribe().
  2. Step 2: Match syntax to options

    supabase.from('messages').on('INSERT', callback).subscribe() matches this syntax with 'messages' and 'INSERT' event.
  3. Final Answer:

    supabase.from('messages').on('INSERT', callback).subscribe() -> Option B
  4. Quick Check:

    Correct syntax = supabase.from('messages').on('INSERT', callback).subscribe() [OK]
Hint: Use .from('table').on('EVENT', callback).subscribe() [OK]
Common Mistakes:
  • Using .table() instead of .from()
  • Listening to wrong event type
  • Incorrect method chaining order
3. Given the code below, what will be logged when a new row is inserted into the 'tasks' table?
supabase.from('tasks').on('INSERT', payload => {
  console.log('New task:', payload.new);
}).subscribe()
medium
A. New task: undefined
B. No output because subscription is missing
C. Error: callback not defined
D. New task: [object Object] with new row data

Solution

  1. Step 1: Understand the callback payload on INSERT

    The payload contains a 'new' property with the inserted row data as an object.
  2. Step 2: Analyze console.log output

    Logging 'New task:' plus payload.new prints the object as '[object Object]' in console.
  3. Final Answer:

    New task: [object Object] with new row data -> Option D
  4. Quick Check:

    Payload.new logs inserted row object [OK]
Hint: payload.new holds inserted row data object [OK]
Common Mistakes:
  • Expecting payload.new to be undefined
  • Confusing payload.new with payload.old
  • Assuming subscription needs extra setup to log
4. What is wrong with this subscription code?
const subscription = supabase.from('orders').on('DELETE', () => {
  console.log('Order deleted');
})
medium
A. Missing .subscribe() call to activate subscription
B. Wrong event type; should be 'REMOVE' instead of 'DELETE'
C. Callback function must receive a payload parameter
D. Subscription must be assigned to a variable named 'sub'

Solution

  1. Step 1: Check subscription activation

    The .subscribe() method is required to start listening to events.
  2. Step 2: Verify event type and callback

    'DELETE' is a valid event, and callback can omit payload if unused.
  3. Final Answer:

    Missing .subscribe() call to activate subscription -> Option A
  4. Quick Check:

    Always call .subscribe() to activate [OK]
Hint: Always end with .subscribe() to start listening [OK]
Common Mistakes:
  • Forgetting .subscribe() call
  • Using wrong event names
  • Thinking callback must have parameters
5. You want to subscribe to both INSERT and UPDATE events on the 'profiles' table and log the changed row each time. Which code correctly achieves this?
hard
A. supabase.from('profiles').on('INSERT,UPDATE', payload => console.log(payload.new)).subscribe()
B. supabase.from('profiles').on(['INSERT', 'UPDATE'], payload => console.log(payload.new)).subscribe()
C. supabase.from('profiles').on('INSERT', payload => console.log(payload.new)).on('UPDATE', payload => console.log(payload.new)).subscribe()
D. supabase.from('profiles').on('INSERT').on('UPDATE', payload => console.log(payload.new)).subscribe()

Solution

  1. Step 1: Understand event subscription chaining

    Supabase allows chaining .on() calls for different events before .subscribe().
  2. Step 2: Evaluate each option's syntax

    supabase.from('profiles').on('INSERT', payload => console.log(payload.new)).on('UPDATE', payload => console.log(payload.new)).subscribe() chains .on('INSERT', ...).on('UPDATE', ...) correctly; others use invalid event formats.
  3. Final Answer:

    supabase.from('profiles').on('INSERT', payload => console.log(payload.new)).on('UPDATE', payload => console.log(payload.new)).subscribe() -> Option C
  4. Quick Check:

    Chain .on() for multiple events [OK]
Hint: Chain .on() calls for each event before .subscribe() [OK]
Common Mistakes:
  • Trying to pass multiple events as array or comma string
  • Calling .subscribe() too early
  • Not chaining .on() properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard