Search code examples
supabasesupabase-database

I can’t get Supabase real-time listen to Postgres changes to work


Inspired by the Supabase docs, I have this code in a React Native app:

useEffect(() => {
  if (session?.user?.id === null) return
  const channel = supabase
    .channel('value-db-changes', { selfBroadcast: true })
    .on(
      'postgres_changes',
      {
        event: 'UPDATE',
        schema: 'public',
        table: 'messages',
        filter: `user_id=${session?.user?.id}`
      },
      (payload) => console.log('Supabase change', payload)
    )
    ?.subscribe()
}, [session?.user?.id])

VSCode warns me that Property 'subscribe' does not exist on type 'never' and the console.log never shows as I edit rows in my database.


Solution

  • You might be using the old version of Supabase but trying v2 syntax.

    Supabase v1 documentation for realtime: https://supabase.com/docs/reference/javascript/subscribe

    As per the latest update for v2 - https://supabase.com/blog/supabase-js-v2,

    // v2
    supabaseClient
      .channel('any_string_you_want')
      .on(
        'postgres_changes',
        {
          event: 'INSERT',
          schema: 'public',
          table: 'movies',
        },
        (payload) => {
          console.log(payload)
        }
      )
      .subscribe()
    
    // v1
    supabase
      .from('movies')
      .on('INSERT', (payload) => {
        console.log(payload)
      })
      .subscribe()
    

    I had similar issues with this code, but installing the right version with v1 syntax worked,

    npm uninstall @supabase/supabase-js@rc
    npm uninstall @supabase/supabase-js
    npm install @supabase/supabase-js