react-websocket

repository·master·Indexed 43 days ago

https://github.com/mehmetkose/react-websocket

A lightweight ReactJS WebSocket listener component (v2.1.0) designed to simplify WebSocket communications. It provides a Websocket component with support for automatic reconnection via exponential backoff or custom intervals, and callbacks for onMessage, onOpen, onClose, and onError.

Tokens
1.2K
Snippets
3
Records
5
Agent score
6%

What's inside react-websocket

  1. Configure reconnection behavior

    master

    The Websocket component supports automatic reconnection.

    • Enable/Disable: Set the reconnect prop to true (default) or false to control whether the component attempts to reconnect after a connection is closed.
    • Custom Intervals: Use reconnectIntervalInMilliSeconds to specify a fixed delay between attempts.
    • Default Backoff: If reconnectIntervalInMilliSeconds is not provided or is set to 0, the component uses an exponential backoff algorithm: Math.min(30, Math.pow(2, k) - 1) * 1000, where k is the number of attempts.
  2. Use the Websocket component

    master

    The Websocket component provides an easy way to handle websocket communications within a React component. You must provide a url and an onMessage callback. The onMessage callback receives data that has already been processed by JSON.parse.

    import React from 'react';
    import Websocket from 'react-websocket';
    
    class ProductDetail extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = {
          count: 90
        };
      }
    
      handleData(data) {
        // Note: The README example shows JSON.parse(data), 
        // but the Properties section states data is already JSON.parse'd.
        // Follow the implementation logic required by your specific data format.
        let result = JSON.parse(data);
        this.setState({count: this.state.count + result.movement});
      }
    
      render() {
        return (
          <div>
            Count: <strong>{this.state.count}</strong>
    
            <Websocket 
              url='ws://localhost:8888/live/product/12345/'
              onMessage={this.handleData.bind(this)}
            />
          </div>
        );
      }
    }
    
    export default ProductDetail;
  3. Websocket component properties

    master

    The Websocket component accepts the following props:

    url (required): The url the websocket connection is listening to.
    
    onMessage (required): The callback called when data is received. Data is `JSON.parse`'d.
    
    onOpen: The callback called when the connection is successfully opened.
    
    onClose: The callback called when the connection is closed either due to server disconnect or network error.
    
    debug (default: false): Set to true to see console logging.
    
    reconnect (default: true): accelerated reconnection time.
  4. Configure Websocket props

    master

    The Websocket component accepts the following props:

    PropTypeRequiredDescription
    urlstringYesThe WebSocket URL to connect to.
    onMessagefunctionYesCallback triggered when a message is received. Receives evt.data as an argument.
    onOpenfunctionNoCallback triggered when the connection is successfully opened.
    onClosefunctionNoCallback triggered when the connection closes. Receives (code, reason).
    onErrorfunctionNoCallback triggered on error. Receives the error event.
    debugbooleanNoIf true, logs connection status to the console. Defaults to false.
    reconnectbooleanNoEnables/disables automatic reconnection on close. Defaults to true.
    protocolstringNoThe WebSocket sub-protocol.
    reconnectIntervalInMilliSecondsnumberNoCustom interval for reconnection attempts. If not provided, uses an exponential backoff strategy.