Skip to content

Latest commit

 

History

History
71 lines (52 loc) · 3.82 KB

File metadata and controls

71 lines (52 loc) · 3.82 KB

🏡 Home

Create Supabase project Create Remix application Query Supabase data with Remix Loaders Generate TypeScript types from Supabase CLI Implement Supabase Auth using GitHub Restrict access with RLS policies Automatically set session cookie with Supabase Auth Helpers Call active Loaders on Supabase Auth state change Mutate Supabase data with Remix Actions Subscribe to database changes with Supabase Realtime Deploy Remix app to Vercel

Subscribe to database changes with Supabase Realtime

📹 Video

Supabase Realtime allow us to subscribe to change events in the database - insert, update and delete - and update the UI dynamically. In this lesson, we enable replication on the messages table to tell Supabase we want to know about changes to this table.

Additionally, we use the Supabase client to set up a subscription for insert events on the messages table. This will receive websocket updates from Supabase, which we can handle in a callback function, and merge our server state with realtime updates, to allow our application to dynamically update as new messages are sent.

Code Snippets

Subscribe to realtime updates

useEffect(() => {
  const channel = supabase
    .channel("*")
    .on(
      "postgres_changes",
      { event: "INSERT", schema: "public", table: "messages" },
      (payload) => {
        const newMessage = payload.new as Message;

        if (!messages.find((message) => message.id === newMessage.id)) {
          setMessages([...messages, newMessage]);
        }
      }
    )
    .subscribe();

  return () => {
    supabase.removeChannel(channel);
  };
}, [supabase, messages, setMessages]);

Enable realtime events on messages table

alter table public.messages
replica identity full;

SQL code snippets can be run against your Supabase database by heading over to your project's SQL Editor, pasting them into a new query, and clicking RUN.

Resources


👉 Next lesson


Enjoying the course? Follow Jon Meyers on Twitter and subscribe to the YouTube channel.