Home > database >  supabase realtime subscribe for react
supabase realtime subscribe for react

Time:11-29

I am trying to display the last value of a supabase table whenever new data is posted to to it.

I am using react, currently just trying to log the data to the console, but I am not getting anything.

My code:

import { supabase } from "../supabase";
import { useEffect } from "react";

const Realtime = () => {
  useEffect(() => {
  const taskListener = supabase
    .channel("public:data")
    .on(
      "postgres_changes",
      { event: "INSERT", schema: "public", table: "data" },
      (payload) => {
        console.log("Change received!", payload);
      }
    )
    .subscribe();

  taskListener.unsubscribe();
}, []);
return <h1>Realtime</h1>;
};

export default Realtime;

This is my first time actually touching backend so this is all quite new to me so if someone could help explain why I might not be seeing anything in my console, or could point me towards so online resources that would be greatly appreciated.

PS if someone want to run the code this is my repo: https://github.com/CO2Sesnsor/breathe-front-end

  • http://localhost:3000/postdata - is the route I use to manually post data from
  • http://localhost:3000/realtime - is the route I am trying log the payload to

CodePudding user response:

You were unsubscribing from the realtime listener as soon as you subscribed to it, and that seemed have been the cause.

To fix this, you would want to return the unsubscribe() call. In useEffect, any of the code inside the return statement is called when the component is unmounted.

useEffect(() => {
  const taskListener = supabase
    .channel("public:data")
    .on(
      "postgres_changes",
      { event: "INSERT", schema: "public", table: "data" },
      (payload) => {
        console.log("Change received!", payload);
      }
    )
    .subscribe();

  // add return right here!
  return taskListener.unsubscribe();
}, []);
  • Related