hasin
hasin

Reputation: 69

supabase realtime subscribe for react

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

Upvotes: 0

Views: 3408

Answers (2)

budokans
budokans

Reputation: 3

useEffect cleanup logic needs to be lazy - i.e. in a callback - otherwise it will execute right after what precedes it. So you'll need to:

return () => taskListener.unsubscribe();

Upvotes: 0

dshukertjr
dshukertjr

Reputation: 18670

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();
}, []);

Upvotes: 3

Related Questions