Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
}, [])
like image 775
vskorepa Avatar asked Oct 16 '25 04:10

vskorepa


1 Answers

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,
}
like image 53
Salih Erdem Kaymak Avatar answered Oct 17 '25 17:10

Salih Erdem Kaymak