Supabase Backend as a Service · Lektion

Änderungen an Tabellen abonnieren

Implementieren Sie clientseitigen Code, der Einfügungen, Aktualisierungen und Löschungen in bestimmten Datenbanktabellen oder -zeilen überwacht.

Lektion 2 von 412 Schritte

Änderungen an Tabellen abonnieren ist eine kostenlose Supabase Backend as a Service-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Supabase Backend as a Service-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Supabase Backend as a Service-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.realtime object.
  • 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!

Kostenlos starten

Lerne Supabase Backend as a Service mit einem KI-Tutor — kostenlos

Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.

Kurse
11
Lektionen
40

Häufig gestellte Fragen

Ist die Lektion „Änderungen an Tabellen abonnieren“ kostenlos?

Ja — der vollständige Text von „Änderungen an Tabellen abonnieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Supabase Backend as a Service-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Supabase Backend as a Service-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Änderungen an Tabellen abonnieren“?

Implementieren Sie clientseitigen Code, der Einfügungen, Aktualisierungen und Löschungen in bestimmten Datenbanktabellen oder -zeilen überwacht. Du übst Supabase Backend as a Service mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Supabase Backend as a Service zu starten?

Keine Vorkenntnisse erforderlich. Supabase Backend as a Service auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „Änderungen an Tabellen abonnieren“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Supabase Backend as a Service-Lektion Code schreiben und ausführen?

Ja. Jede Supabase Backend as a Service-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Realtime-Abonnements verstehen
  2. Änderungen an Tabellen abonnieren
  3. Eine Live-Chat-Funktion erstellen
  4. Presence- und Broadcast-Kanäle
← Zurück zu Supabase Backend as a Service