Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-event-socket

Package Overview
Dependencies
Maintainers
0
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-event-socket

A package to help use WebSocket with React

  • 2.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

react-event-socket

A simple React component to handle WebSockets events.

Installation

npm install react-event-socket

Usage

The below is a simple example of how to use react-event-socket. In the below example the server is sending a message event with a payload of {message: 'Hello World'}. We can set up react-event-socket to listen for this event by using the addEvent function and setting the predicate to identify this event by the payload. We can do this via 'message' in data.

//service.ts
import { ReactEventSocket, Middleware } from 'react-event-socket';

interface MessageEvent {
    userId: number,
    user: { name: string, email: string },
    data: { message: string }
}

const wrapPayload: Middleware = ({ name, data }) => ({ action: name, data });

const [socket, hooks] = new ReactEventSocket('ws://localhost:1234', true)
    .addReceivedMessage((received) =>
        received
            .addEvent({
                name: 'received-message',
                predicate: (data: MessageEvent) => 'message' in data,
                // the props on the select callback will match the props on the predicate
                select: ({ user: { name }, data: { message } }) => {
                    return { name, message };
                },
                array: true,
            })
            .addEvent({
                name: 'joined-room',
                predicate: (data: JoinedRoom) => data.action === 'joined-room',
            }),
    )
    .addSendMessage((send) => {
        return send
            .addPayload<{
                channel: string;
            }>()({ name: 'join' })
            .addPayload<{ message: string }>()({
                name: 'message',
                middleware: [wrapPayload],
            });
    })
    .build();
// component.tsx
import { events, socket } from './service.ts';

function App() {
    const status = socket.useStatus();
    const messages = events.useReceivedMessage(); // the type of this will match the type returned from the select {name:string, message: string}[]
    return <>
        <p>Status: {status}</p>
        <p>latest message: {message}</p>
        {status === 'open' && <button onClick={() => socket.sendMessage({ message: 'Hello World' })}>Send</button>}
        {status === 'closed' && <button onClick={() => socket.reconnect()}>Reconnect</button>}
    </>;
}

export default App;

Keywords

FAQs

Package last updated on 17 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc