Skip to main content

Live Updates

Core imports come from the subpath; React helpers come from the root React package.

import {
LiveUpdateService,
SSEService,
WebsocketService,
type EventMapping,
} from '@codella-software/utils/live-updates'
import { createFirebaseAuthProvider } from '@codella-software/utils/api-service'
import {
LiveUpdateProvider,
useLiveListener,
useLiveRequest,
useLiveUpdateContext,
useLiveUpdateListener,
useLiveUpdates,
} from '@codella-software/react'

Core service

const authProvider = createFirebaseAuthProvider({ auth })

const sseService = new SSEService({
url: 'https://api.example.com/sse',
authProvider,
})

const wsService = new WebsocketService({
url: 'wss://api.example.com/ws',
authProvider,
})

const liveUpdates = new LiveUpdateService(wsService, sseService)

liveUpdates.initialize({
sseEnabled: true,
wsEnabled: true,
authProvider,
eventMappings: {
notifications: {
sseEvent: 'GET_NOTIFICATIONS',
wsAction: 'NOTIFICATIONS_RESPONSE',
},
},
})

Public API:

  • initialize(config)
  • on(eventName)
  • send(action, payload?)
  • disconnect()
  • destroy()
  • type
  • isConnected$
  • canSend

React provider

function App() {
return (
<LiveUpdateProvider
authProvider={authProvider}
sseUrl="https://api.example.com/sse"
wsUrl="wss://api.example.com/ws"
eventMappings={{
notifications: {
sseEvent: 'GET_NOTIFICATIONS',
wsAction: 'NOTIFICATIONS_RESPONSE',
},
}}
>
<Notifications />
</LiveUpdateProvider>
)
}

Provider props:

  • authProvider
  • sseUrl?
  • wsUrl?
  • sseEnabled?
  • wsEnabled?
  • eventMappings?
  • children

React hooks

useLiveUpdateContext()

Returns { service, isConnected, type, canSend }.

useLiveUpdates(eventName)

const { data, error } = useLiveUpdates<Notification[]>('notifications')

useLiveListener(action, enabled?)

const { data, error } = useLiveListener<User>('USER_UPDATED')

useLiveUpdateListener(action, onUpdate, options?)

const { subscribe } = useLiveUpdateListener<User>('USER_UPDATED', (user) => {
console.log(user)
})

useEffect(() => subscribe(), [subscribe])

useLiveRequest()

const { request, canSend } = useLiveRequest<{ page: number }, User[]>()

if (canSend) {
await request('USERS_FETCH', 'USERS_RESPONSE', { page: 1 })
}