0.2.2 • Published 5 years ago

@lawcket/react-websocket v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

npm downloads total npm version npm license

@lawcket/react-websocket

A slim Websocket implementation for React 16+. The libray uses the standard browser WebSocket so 'should' be supported in React-Native.

Installation

npm install --save @lawcket/react-websocket

or

yarn add @lawcket/react-websocket

Usage

Example:

import React, { useState } from 'react';
import Websocket from '@lawcket/react-websocket';

const Messages = () => {
  const [messages, addMessage] = useState([]);
  return (
    <Websocket 
      url='wss://...' 
      retry
      onOpen={({ send }) => console.log('open')}
      onClose={({ code, reason }) => console.log('closed', code, reason)}
      onMessage={({ send, data }) => console.log('message', data)}
      onError={(error) => console.log('error', error)} >
      {({ send, close }) => {
        return (
            <pre>{JSON.stringify(messages, null, 2)}</pre>
        );
      }}
    </Websocket>
  );
}

PropTypes

NameTypeDescriptionDefault
urlstringThe websocket url to connect to
protocolstringThe protocol for the websocket to use
retrybooleanIf an error occurs, should it reconnecttrue
onOpenfunctionNotifies when the connection has been opened
onMessagefunctionNotifies when an incoming message has been received
onClosefunctionNotifies the connection was closed
onErrorfunctionNotifies of an error with the connection, will close the connection

onOpen

ParameterTypeDescription
sendfunction(any)A function to send data to the server

onMessage

ParameterTypeDescription
dataanyIncoming message (usually stringified JSON data)
sendfunction(any)A function to send data to the server

onError

ParameterTypeDescription
errorErrorThe error that occured during connection or usage

onClose

Reference: Close codes & reasons

ParameterTypeDescription
codenumberThe close code sent by the server
reasonstringThe reason the connection was closed
0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago