realtime-js: When used with react strict mode, the realtime database does not subscribe properly.

Bug report

Describe the bug

When we develop with the React strict mode, we can’t build subscriptions correctly.

To Reproduce

Turn on strict mode:

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Using subscriptions in components:

function App() {
  useEffect(() => {
    const subs = supabase
      .from("objects")
      .on("UPDATE", (payload) => {
        dispatch(updateGameObject(payload.new.data));
      })
      .subscribe(console.log);
    subs.onClose(() => {
      console.log("on closed");
      supabase.removeAllSubscriptions();
    });
    return () => {
      subs.unsubscribe();
    };
  }, []);
  return <div />
}

Expected behavior

In strict mode, useEffect is triggered twice. In theory, it should quickly establish and close a connection once, and then establish it again.

However, in practice, it is not possible to subscribe properly. In strict mode, subscribe() will receive the CLOSED signal directly at the first time.

Screenshots

The output in the console is as follows:

image

System information

  • OS: Windows
  • Browser (if applies): Edge
  • Version of supabase-js: ^1.35.4
  • Version of Node.js: 16
  • Version of react: 18

Additional context

In supabase/supabase#7771 it is suggested that turning on strict mode can cause problems.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 17 (5 by maintainers)

Most upvoted comments

Using this workaround, for the time being, solves the issue =>

useEffect(() => {
  // This is a hack for React >= v18 in Strict mode
  // ensures to always call on the last  mount and
  // correctly remove subscription on unmount
  let subscription = null;
  const timer = setTimeout(() => subscription = subscribeToTable(), 1000);

  function subscribeToTable() {
    return (
      supabase
        .from("my_table")
        .on("*", (payload) => {
          console.log('Change received!', payload)
        })
        .subscribe((msg) => {
          if (msg === 'SUBSCRIBED') {
            isSubscribed.current = true;
          }
        })
    );
  }

  return () => {
    if (!subscription) {
      return clearTimeout(timer);
    }

    supabase.removeSubscription(subscription);
    isSubscribed.current = false;
  };
}, []);

I have removed <ReactStrictMode> and problem solved

if i pass config: { broadcast: { ack: true }} the default self: false disappears.

@pixtron that’s fine as the Realtime server will take the absence to mean self is false but i’ll go back and make the default config better. thanks for pointing this out.

@chiubaca just wanted to check if you tried it with cleanup and removeChannel instead of unsubscribe?

In my case, I upgraded to Next.js v12.2.3 and it solved the problem. Release v12.2.3 · vercel/next.js