How to use Realtime Functionality in Supabase Postgress Database

How to use Realtime Functionality in Supabase Postgress Database

·

2 min read

WELCOME 👋 friends to this new blog post. In this blog post, you will learn how to fetch data or get alerted whenever a row is inserted, updated, and deleted in the supabase Postgres database with the help of a supabase subscription, 😁Pretty easy to setup.

🤔When to use it?

Suppose, I gave you a project of making a real-time chat app with supabase. Then you need to fetch data whenever a new chat is inserted, deleted, or updated.

First, you need to go to the supabase database settings:

Note: I have selected my tables, the table settings would be different from yours.

👀Note: The tables which are enabled by clicking the green button will be able to make real-time data fetching.

import type { NextPage } from "next";
import { useEffect, useState } from "react";
import styles from "../styles/Home.module.css";
import supabase from "../utils/supabase";

const Home: NextPage = () => {
  const [chats, setChats] = useState<any | null>(null);

  useEffect(() => {
    const subscritpion = supabase
      .from("chats") // here, you can put '*' if you want to listen to changes on every table or you can put name of a specifict table
      .on("INSERT", (payload) => {
        console.log(payload);
      })
      .subscribe();

    return () => {
      supabase.removeSubscription(subscritpion);
    };
  }, []);

  return <div className={styles.container}></div>;
};

export default Home;

on 👆 can have three 4 types:

  1. INSERT — Listening to the table if any new row is inserted

  2. UPDATE— Listening to table if any row is updated

  3. DELETE— Listening to table if any row is deleted

  4. * — Listening to the table for all the above changes.

you will get a response something like this:

For people who understand Hindi - https://youtu.be/ECIfs9bb7OA

Thanks for reading, if any error comes, feel free to ask here 👇: Join the Next Dev's server Discord Server!

Did you find this article valuable?

Support Next Dev by becoming a sponsor. Any amount is appreciated!