MinChanSike / react-use-signalr

React hooks for SignalR.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react-use-signalr

Node.js CI

Getting Started

1. Install the hooks

npm install react-use-signalr --save

2. Install SignalR

If you haven't installed the signalR package yet, you have to add it manually:

npm install @microsoft/signalr --save

3. Setting up the HubConnection

Use the HubConnectionBuilder descibed in the Microsoft documentation to build the connection.

const signalRConnection = new HubConnectionBuilder()
  .withUrl("https://localhost:5001/chathub")
  .withAutomaticReconnect()
  .build();

4. Establish the connection

To start the SignalR connection, pass the HubConnection instance to the useHub hook. The hook will provide the current hub state as well as an error value if the connection fail.

const { hubConnectionState, error } = useHub(signalRConnection);

5. Call client methods from the hub

useClientMethod(signalRConnection, "ReceiveMessage", (user, message) => {
    [...]
});

6. Call hub methods from the client

const { invoke, loading, error } = useHubMethod(signalRConnection, "SendMessage");

[...]

invoke([...]);

About

React hooks for SignalR.

License:Apache License 2.0


Languages

Language:TypeScript 99.2%Language:JavaScript 0.8%