Now that we understand the fundamentals of Supabase realtime subscriptions, let's put that knowledge into practice by building a simple, yet powerful, collaborative to-do application. In this app, multiple users can view and update the same to-do list in real-time. Any change made by one user will instantly be reflected on the screens of all other connected users.
Our collaborative to-do app will consist of a basic frontend that displays a list of to-do items. Each item will have a checkbox to mark it as complete and a button to delete it. The magic happens in how these actions are synchronized across all connected clients using Supabase realtime.
First, let's set up our Supabase project and create a simple table to store our to-do items. We'll need a table named todos with columns like id (UUID, primary key), task (text), and is_complete (boolean, default false). Crucially, we need to enable real-time subscriptions for this table.
CREATE TABLE public.todos (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
task text NOT NULL,
is_complete boolean DEFAULT false,
PRIMARY KEY (id)
);With our table in place, let's consider the frontend implementation. We'll use JavaScript to interact with Supabase. The core components will be fetching the initial list of to-dos, subscribing to realtime changes, and handling user interactions like adding, toggling completion, and deleting to-dos.
Here's how we'll initialize the Supabase client and fetch the initial list of to-dos. This is standard practice before we can leverage realtime updates.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseAnonKey)
async function fetchTodos() {
const { data, error } = await supabase.from('todos').select('*')
if (error) console.error('Error fetching todos:', error)
else {
// Render todos to the UI
console.log('Initial todos:', data)
}
}The real magic happens when we subscribe to changes in the todos table. We'll use supabase.channel() and on() to listen for INSERT, UPDATE, and DELETE events. When an event occurs, we'll update our UI accordingly.