S
S
sergeyviktorovich2021-11-01 09:27:23
React
sergeyviktorovich, 2021-11-01 09:27:23

When and how should a websocket firebase connection be closed?

When and how should a websocket firebase connection be closed?
making a react app

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tehfreak, 2021-11-01
@sergeyviktorovich

Firebase manages its own websocket connection. The application, on the other hand, manages listeners: it subscribes to database updates when necessary and unsubscribes when updates are no longer required.
Something like this:

import { doc, onSnapshot } from 'firebase/firestore'

export default function EntitityPage({ entityId }) {

    const [ entity, setEntity ] = React.useState(null)
    
    React.useEffect(() => {
        const unsubscribe = onSnapshot(doc(db, 'entities', entityId), (snapshot) => {
            setEntity(snapshot.data())
        })
        return () => {
            unsubscribe()
        }
    }, [entityId])
    
    return (
        <div>{JSON.stringify(entity)}</div>
    )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question