use-sockjs
TypeScript icon, indicating that this package has built-in type declarations

2.6.0 • Public • Published

use-sockjs

Node.js Package NPM NPM

React Hook for SockJs

Installation

yarn add use-sockjs

Usage

Wrap your app inside the SockJsProvider component.

import React from 'react'
import { SockJsProvider } from 'use-sockjs'

const App = () => {
  return (
    <SockJsProvider
        onError={(error: Frame | string) => {
        }}
    >
      {/* ... */}
    </SockJsProvider>
  )
}

export default App

Call the useSockJs hook in the components.

import React from 'react'
import { useSockJs } from 'use-sockjs'
import { Client, Frame, Message, Subscription } from 'stompjs'

export const MyComponent: React.FunctionComponent = () => {
  const { connect, disconnect, subscribe } = useSockJs()

  const subscriptionRef = useRef<Subscription | null>(null)

  // connect websocket when init
  useEffect(() => {
    connect({
      url: 'http://localhost/ws',
      heartbeat: {
        incoming: 600000,
        outgoing: 600000
      },
      onConnected(client) {
        subscribe({
          destination: 'destination',
          onMessage: message => {
          },
          onSubscribed: (subscription) => {
            subscriptionRef.current = subscription
          }
        })
      }
    })

    return ()=>{
      if(subscriptionRef.current){
        unsubscribe(subscriptionRef.current)
      }
      disconnect()
    }
  }, [])

  return (
    <div></div>
  )
}

Readme

Keywords

none

Package Sidebar

Install

npm i use-sockjs

Weekly Downloads

4

Version

2.6.0

License

MIT

Unpacked Size

24.8 kB

Total Files

30

Last publish

Collaborators

  • darrenfang