Search code examples
reactjsnext.jsuse-effectsupabase

Next JS + Supabase real time subscription subscribes with state "closed"


I am working on this helpdesk for a school project using Next JS and Supabase and got stuck on realtime chat between the operator and the client.

I subscribe to the table in useEffect hook and return the unsubscribe function to clean up.

But when i change tickets sometimes the subscription is established but with a state already closed which causes the subscription to stop sending the callbacks.

I think the problem might be with the new subscription being called right after (or maybe even during) the cleanup function which causes even the new one to be closed. But I am not sure how to get around that.

Any ideas? this is the useEffect used:

useEffect(() => {
    getMessages(id)

    const MessageSubscription = supabase
        .from<definitions['messages']>('messages')
        .on('INSERT', (message) => {
            getMessages(id)
        })
        .subscribe()

    async function removeMessageSubscription() {
        await supabase.removeSubscription(MessageSubscription)
    }
    return () => {
        removeMessageSubscription()
    }
}, [])

Solution

  • Probably useEffect fires twice and it may occure some unexpected behaviors for realtime events.

    Just disable the strict mode and try again.

    // next.config.js
    module.exports = {
        reactStrictMode: false,
    }