useSignalRHub
An easy to use React hook for @microsoft/signalr
Please use Microsoft's Documentation and API Reference as guidance.
Getting started
Install using your preferred package manager
$ npm install use-signalr-hub @microsoft/signalr
$ yarn add use-signalr-hub @microsoft/signalr
Import into your project
import signalR from "use-signalr-hub"
Use in your React component
const signalRHub = signalR.useHub("https://www.example.com/hub", {
onConnected: (hub) => {
// Connected to hub
hub.on("ReceiveMessage", (user, message) => {
// Listen to "ReceiveMessage" on hub
})
},
onDisconnected: (error) => {
// Disconnected from hub
},
onError: (error) => {
// Failed to connect to hub
}
})
const handleSubmit = (user, message) => {
signalRHub.invoke("SendMessage", user, message)
.catch((error) => {
// Failed to invoke "SendMessage" on hub
})
}
Configure defaults
signalR.setDefaults({
httpTransportTypeOrOptions: {
accessTokenFactory: () => user.userData.token
},
automaticReconnect: false
})
Api
const signalRHub = signalR.useHub(hubUrl, {
onConnected,
onDisconnected,
onReconnecting,
onReconnected,
onError,
enabled,
automaticReconnect,
httpTransportTypeOrOptions,
hubProtocol,
logging
})
Options
onConnected?: (hub: HubConnection) => void
onDisconnected?: (error?: Error) => void
onReconnecting?: (error?: Error) => void
onReconnected?: (connectionId?: string) => void
onError?: (error?: Error) => void
enabled?: boolean
automaticReconnect?: number[] | IRetryPolicy | boolean
httpTransportTypeOrOptions?: IHttpConnectionOptions | HttpTransportType
hubProtocol?: IHubProtocol
logging?: LogLevel | string | ILogger
HubConnection | IRetryPolicy | IHttpConnectionOptions | HttpTransportType | IHubProtocol | LogLevel | ILogger
Returns
signalRHub: HubConnection | null